我有一个类似于这个的类:
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);
}
}
};
Run Code Online (Sandbox Code Playgroud)
并使用如下:
main()
{
C add(1);
C sub(2);
auto x=add.calc(1,2);
auto z=sub.calc(2,1);
}
Run Code Online (Sandbox Code Playgroud)
这段代码有效,但应该调用的函数在运行时被解析,我正在寻找一个解决方案来解决在编译时调用的函数.像这样的东西:
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);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是否在编译期间实际解析了函数,或者它仍然在运行时解析它?
有什么方法可以使用模板类来做到这一点吗?假设我想在Visual Studio 2013和GNU上编译它们,它们具有一些c ++ 11功能.
在您的示例func中,在运行时解决main:
C add(1);
C sub(2);
Run Code Online (Sandbox Code Playgroud)
编译时间意味着:
C<1> add;
C<2> sub;
Run Code Online (Sandbox Code Playgroud)
如果上面的更改是可以接受的,那么C++ 98/03经典的想法就是使用函数重载:
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>());
}
};
Run Code Online (Sandbox Code Playgroud)
笔记:
calc_impl只有两个函数带有三个参数.省略第三个参数的名称,因为它未被使用.它们是由第三个参数超载,因为IntToType<1>和IntToType<2>两种不同的类型.calc_impl功能放入班级的私人部分,以获得更好的人体工程学.