假设我有一个带有 3 个模板参数的模板。 我希望第三个模板参数被另一个模板采用,比如“CHECK”,如果 CHECK 失败则返回任何整数,否则为“1”。在“1”的情况下,X 类是专门的。 如以下代码所示。 我怎样才能实现它,即如何强制始终使用默认模板参数(目标是使其成为强制性的而不是默认的)。如果需要这样的设计应该做什么? 简而言之,“我想阻止用户提供第三个参数”。
template<typename T, typename D , int = CHECK<T, D>::IS_TRUE >
class X
{
public :
X()
{
using namespace std;
cout << "Inside General Implementation " << endl;
}
};
template<typename T, typename D>
class X<T, D, 1>
{
public :
X()
{
using namespace std;
cout << "Inside SPECIAL Implementation " << endl;
}
//Specialized Implementaion
};
int main(int argc, char* argv[]) try
{
X<MyWiget, YourWiget > xObj ; //CHECK used desired behaviour
X<MyWiget, YourWiget, 1 > xObj ; //CHECK not used specialized behaviour
X<MyWiget, YourWiget, 2 > xObj ; //CHECK not used i.e. default template argument not used
}
catch(...)
{
//should not land here
using namespace std;
cout << " Problems in exception handling in code";
}
最佳答案
IIUC,您希望阻止用户提供第三个参数。
将类 X
重命名为 X_impl
并提供一个新的 X
,参数更少:
template<typename T, typename D, int Int >
class X_impl;
template<typename T, typename D >
class X : public X_impl< T, D, CHECK<T, D>::IS_TRUE > {};
关于c++ - 是否有从其他模板参数推导出来的强制模板参数之类的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4159309/