c++ - 根据类模板参数值禁用成员函数

标签 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> 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/

相关文章:

c++ - 错误 C2248 : 'X::operator =' : cannot access private member declared in class 'X'

c++ - 为什么在某些情况下可以调用没有对象的成员函数?

c++ - 如何将客户端类与模板类分离?

c++ - 具有同名对象文件的静态库 (ar)

C++ - 将 ANSI 编码的文本读取为宽字符串

c++ - 使用(未)捕获的异常进行堆栈展开

c++ - 从C语言文件中提取单词

c++ - 寻找对我的线程安全、无锁队列实现的批评

javascript - 使用下划线外部模板在主干中设置模型内容

c++ - 无法推断模板参数 'N'