C++ 基于类模板参数值禁用成员函数
我希望有一个类,它根据类的模板参数值禁用/启用成员函数。我有以下资料:C++ 基于类模板参数值禁用成员函数,c++,c++11,templates,metaprogramming,enable-if,C++,C++11,Templates,Metaprogramming,Enable If,我希望有一个类,它根据类的模板参数值禁用/启用成员函数。我有以下资料: enum MyType{ type1, type2 }; template <MyType type> class Test{ public: enum TestTraits{ testType = type }; template <typename T> constexpr bool func(SomethingElse<T> e
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
}
};
enum MyType{type1,type2};
模板
课堂测试{
公众:
枚举TestTraits{testType=type};
模板
constexpr bool func(其他内容)
{
if(testType==type1)返回false;
//返回真或假的逻辑
}
};
我基本上希望它是一个编译时检查,而不是运行时检查,如果可能的话,客户端甚至不能调用它。我确信解决方案是enable_if,但当我看到这一点时,似乎需要enable_if来决定返回类型或函数参数之一如果我理解正确,您将需要以下选项之一:
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\u如果在您不想启用/禁用的函数的返回类型中
(您仍然可以使用函数returnbool
):
从本质上讲,它会有很多不同的排列吗?对于这样一个2的简单示例,您可以专门化两个不同选项的类。只有两种类型,我以前已经实现了该解决方案,但是其中有一些函数不同。我希望我可以只使用“一个”类,你真正需要的是,但这是C++17的特性。否则,您可以有多个重载并使用SyFAE,就像JORK刚刚回答的那样。我不确定<代码>其他代码< /COD>的意图,所以考虑这个伪代码…因此,我使用以下第一种方法得到以下编译错误:“错误:在STD之前需要类型名::Enable,如果因为STD::EnabLayIf是一个依赖的范围……有什么想法吗?是的,忘记了一个
类型名
,正如错误所说。。。修正:)是的,对此很抱歉,忘记了这个小问题。实际上,当我尝试在type1对象上执行此操作时,会出现以下错误:在struct std::enable_中没有名为“type”的类型,如果
有什么想法吗?
template <typename T>
constexpr bool func(SomethingElse<T>)
{
static_assert(type != type1, "can't call this with type1...");
return true;
}
template<MyType mytype>
struct SpecialStuff {
bool func();
};
template<>
struct SpecialStuff<type1> {
};
template<MyType mytype>
struct CommonStuff : private SpecialStuff<mytype> {
};