-
Template question
Is there a way to tell what type of VAR comes in through a template function?
like this for example
PHP Code:
template <typename T>
void Combine(T &a, T &b)
{
if int or long
a = a + b;
if string
a += b;
if char
strcpy(a,b);
etc..
}
I though I saw somewhere how to do this, but I can't find it.
Thanks
-
typeid might help you here...
But for this, you're best specialising:
Code:
template<typename T>
void Combine(T &target, const T &ref) {
target += ref;
}
Combine<char*>(char *&target, const char *&ref) {
strcat(target, ref);
}
...or something.
-
the template argument T you are using is the type
If you don't want to implement functionality within T you can call a functor and partial specialize for each T you desire, ex:
template<typename T>
struct ftr{
static inline char* name(){return "no specific T";}
};
template<>
struct ftr<int>{
static inline char* name(){return "T is int";}
};
etc...
template<typename T>
void Combine(T &target, const T &ref) {
...
ftr<T>::name
...
}
-
typeid works only for classes with virtual functions when RTTI is enabled.