I have a class that is similar to this one:
int add(int a,int b)
{
return a+b;
}
int sub(int a,int b)
{
return a-b;
}
class C
{
int m_functionType;
C(int functionType)
{
m_functionType=functionType;
}
int calc(int a, int b)
{
switch(m_functionType)
{
case 1: // add
return add(a,b);
break;
case 2: // subtract
return sub(a,b);
}
}
};
and the use it as follow:
main()
{
C add(1);
C sub(2);
auto x=add.calc(1,2);
auto z=sub.calc(2,1);
}
This code works, but the function which should be called is resolved at run time, I am looking for a solution that the solves the functions to call at compile time. something such as this:
template <int func>
class C
{
int calc(int a, int b)
{
switch(func)
{
case 1: // add
return add(a,b);
break;
case 2: // subtract
return sub(a,b);
}
}
};
main()
{
C<1> add;
C<2> sub;
auto x=add.calc(1,2);
auto z=sub.calc(2,1);
}
Is the above code actually resolves the function during compile time or it still resolve it during run time?
Is there any way that I can do this using a template class? Assuming I want to compile it on Visual studio 2013 and GNU which they have some c++11 capability.
In your example func
is resolved at run-time in main
:
C add(1);
C sub(2);
Compile-time would mean:
C<1> add;
C<2> sub;
If the change above is acceptable, C++98/03 classic idea is to use function overloads:
template <int v>
struct IntToType {
enum {val = v};
};
int calc_impl(a, b, IntToType<1>) {
return add(a, b);
}
int calc_impl(a, b, IntToType<2>) {
return sub(a, b);
}
template <int func>
class C {
int calc(int a, int b) {
return calc_impl(a, b, IntToType<func>());
}
};
Notes:
calc_impl
are just two functions taking three arguments. The name of the third argument is omitted because it is not used. They are overloaded by third parameter, because IntToType<1>
and IntToType<2>
are two different types.calc_impl
functions into private section of your class for better ergonomics.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With