Reputation: 63442
How can I find the type of the template argument at template instantiation time? For example, I'd like the following template to instantiate into 2 different functions, depending on the argument:
template <typename T> void test(T a) {
if-T-is-int {
doSomethingWithInt(a);
} else {
doSomethingElse(a);
}
}
When instantiated with an int
, the resulting function would be:
void test(int a) { doSomethingWithInt(a); }
and when instantiated with a float
for example, it would be:
void test(float a) { doSomethingElse(a); }
Upvotes: 0
Views: 372
Reputation: 61910
In your case, it sounds like all you need is two overloaded versions for int
and float
. There's no behaviour for other types described, so templates aren't necessary.
void test (int i) {
doSomethingWithInt(i);
}
void test (float f) {
doSomethingElse(f);
}
If you do need the case of other types, add in a normal templated version. The specific overloads take precedence. For an example, see here.
Upvotes: 1
Reputation: 4752
template <typename T> void test(T a) {
doSomethingElse(a);
}
template <> void test(int a) {
doSomethingWithInt(a);
}
Should work, but you need to consider cases where you get an int &
, const int
, etc.
Upvotes: 1