【发布时间】:2022-01-17 09:17:26
【问题描述】:
以下代码类似于我的真实应用程序。我有一个高度依赖int值s的类定义,当调用具有两个不同s值的两个类的实例时,我需要编写两次函数调用,我们有没有更简单的方法,比如using rightInst = std::conditional_t<use10, instA, instB>;我们在实例化之前使用的。
template<int s>
class classAdef{
public:
// some code related to 's'
classAdef(){
// some code related to 's'
}
int operator(int a, int b, int c){
// some code related to 's'
printf("class is called \n");
return 0;
}
}
bool use10 = true;
using def10 = classAdef<10>;
using def100 = classAdef<100>;
def10 instA;
def100 instB;
if (use10){
instA(1, 2, 3);
} else{
instB(1, 2, 3);
}
// this code doesnot work, but want something like this to simpilify the function calling
using rightInst = std::conditional_t<use10, instA, instB>;
rightInst(1, 2, 3);
【问题讨论】:
-
rightInst{}(1, 2, 3);将调用(默认构造函数和)operator()采用 3ints,rightInst(1, 2, 3)将只调用(不存在的)构造函数采用 3ints。