我希望有一个基于类的模板参数的值来禁用/启用成员函数的类。我有以下内容:
enum MyType{ type1, type2 };
template <MyType type>
class Test{
public:
enum TestTraits{ testType = type };
template <typename T>
constexpr bool func(SomethingElse<T> else)
{
if(testType == type1) return false;
// some logic that would return true or false
}
};
我基本上希望使它成为编译时检查,而不是运行时检查,并且即使可能,客户端也不选择调用它。我确定解决方案是enable_if,但是当我看到该解决方案时,似乎需要enable_if来确定返回类型或函数参数之一
如果我对您的理解正确,您将需要以下之一:
enable_if
在您不想启用/禁用的函数的返回类型中(您仍然可以使用函数return bool
):
template <typename T>
constexpr typename std::enable_if<type != type1, bool>::type
func(SomethingElse<T>)
{
return true;
}
或静态断言声明:
template <typename T>
constexpr bool func(SomethingElse<T>)
{
static_assert(type != type1, "can't call this with type1...");
return true;
}
第三选项正在移动要在基类中禁用的功能。然后将type1
的基数专门化,并将其留空:
template<MyType mytype>
struct SpecialStuff {
bool func();
};
template<>
struct SpecialStuff<type1> {
};
template<MyType mytype>
struct CommonStuff : private SpecialStuff<mytype> {
};