这是根据需要解决问题的一种方法:
template<typename T, typename U = NullType>
struct TemplateStruct
{
TemplateStruct(int i)
{
boost::enable_if< boost::is_same<U,NullType>, void*>::type var = nullptr;
std::cout << "One Param == " << i << std::endl;
}
TemplateStruct(int i, int j)
{
boost::disable_if< boost::is_same<U,NullType>, void*>::type var = nullptr;
std::cout << "Two Param == " << i << "," << j << std::endl;
}
};
int main()
{
TemplateStruct<TestType>(1);
TemplateStruct<TestType,NonNull>(1,2);
//will not compile TemplateStruct<TestType>(1,2);
//will not compile TemplateStruct<TestType,NonNull>(1);
}
EDIT1:或者假设您选择的编译器和您使用的 STL 实现支持 static_assert 和类型特征(即 VS 2010 支持),如果尝试使用禁用的 ctor,您可以获得更好的错误消息:
template<typename T, typename U = NullType>
struct TemplateStruct
{
TemplateStruct(int i)
{
static_assert( std::is_same<U,NullType>::value, "Cannot use one parameter ctor if U is NullType!" );
std::cout << "One Param == " << i << std::endl;
}
TemplateStruct(int i, int j)
{
static_assert( !std::is_same<U,NullType>::value, "Cannot use two parameter ctor if U is not NullType!" );
std::cout << "Two Param == " << i << "," << j << std::endl;
}
};
EDIT2:或者如果您的 STL 中没有 is_same 但您有 static_assert:
template<typename T, typename U = NullType>
struct TemplateStruct
{
TemplateStruct(int i)
{
static_assert( boost::is_same<U,NullType>::value, "Cannot use one parameter ctor if U is NullType!" );
std::cout << "One Param == " << i << std::endl;
}
TemplateStruct(int i, int j)
{
static_assert( !boost::is_same<U,NullType>::value, "Cannot use two parameter ctor if U is not NullType!" );
std::cout << "Two Param == " << i << "," << j << std::endl;
}
};