我想要一个类,它根据类的模板参数的值禁用/启用成员函数。我有以下内容:
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
在您不想启用/禁用的函数的返回类型中
(您仍然可以让函数返回 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> {
};
关于c++ - 根据类模板参数值禁用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61488965/