Reputation: 1018
If I have a function such as:
template <class T>
T myFunc(){
return T_run();
}
So if I call myFunc<int>()
, it should internally invoke int_run().
If I call myFunc<MyClass>()
, it should internally invoke MyClass_run().
This requires T_run to be expanded by substituting T with the name of the template argument.
Is this possible in C++?
Thanks,
Yash
Upvotes: 0
Views: 57
Reputation: 2281
You cannot do this using templates but if you really must you can achieve the same thing with a macro:
#define myFunc(T) T##_run()
myFunc(int); // calls int_run()
myFunc(MyClass); // calls MyClass_run()
The ##
operator joins tokens, so it allows you to construct function names during preprocessing.
Upvotes: 0
Reputation: 65630
You can't perform arbitrary function name substitutions like that in c++. What you can do is provide specialisations on the function template, like so:
template <class T>
T myFunc();
template <>
int myFunc<int>() { return 3; }
template <>
MyClass myFunc<MyClass>() { return MyClass(); }
void foo() {
int a = myFunc<int>();
MyClass b = myFunc<MyClass>();
}
Upvotes: 1