Reputation: 495
I have a template function like
template<typename T> T ABS(const T& DiIN){
return (0 > DiIN) ? T(DiIN * (-1)) : T((DiIN));
}
template<typename T> T ADD(const T DiIN1, const T DiIN2) {
return DiIN1 + DiIN2;
}
I need to call the function ABS and/or ADD using a single function pointer. Currently I use two different function pointer names, but found it is getting complicated when I include more template function with different argument length.
my current implementation is like
template<typename T>
struct test {
std::string funcName;
T(funcptr1 *)(T);
T(funcptr2 *)(T, T);
};
test<int> ltest[] = { {"ABS", ABS, NULL}, {"ADD", NULL, ADD} };
Is there a way to
1) Use a single function pointer
2) get rid of the initialization test<int>
and use test<T>
so that I can use any variable type during runtime?
I am looking for a simple initialization like
template<> //template<typename T>
test<T> ltest[] = = { {"ABS", ABS}, {"ADD", ADD}, ..... };
Upvotes: 1
Views: 70
Reputation: 206607
Is there a way to use a single function pointer?
There is probably a way of doing that using std::function
. However, you can get the simplicity you are looking for by providing a few constructors.
template <typename T>
struct test {
using function1_type = T(*)(T);
using function2_type = T(*)(T, T);
test(std::string fname, function1_type f1) : funcName(fname), funcptr1(f1), funcptr2(nullptr) {}
test(std::string fname, function2_type f2) : funcName(fname), funcptr1(nullptr), funcptr2(f2) {}
test(std::string fname, function1_type f1, function2_type f2) : funcName(fname), funcptr1(f1), funcptr2(f2) {}
std::string funcName;
function1_type funcptr1;
function2_type funcptr2;
};
Now, you will be able to use:
test<int> ltest[] = { {"ABS", ABS}, {"ADD", ADD}, {"MIXED", ABS, ADD} };
If you want to disallow use of {"MIXED", ABS, ADD}
to construct an object, you can remove the last constructor.
BTW, in order to use the above, you'll need to modify ABS
and ADD
so that the argument types don't have const
or const&
. They need to be:
template<typename T> T ABS(T DiIN){
return (0 > DiIN) ? T(DiIN * (-1)) : T((DiIN));
}
template<typename T> T ADD(T DiIN1, T DiIN2) {
return DiIN1 + DiIN2;
}
Is there a way to get rid of the initialization
test<int>
anduse test<T>
so that I can use any variable type during runtime?
No, you cannot do that. The types used to instantiate a template must be known at compile time.
Upvotes: 2