【问题标题】:Disable a member function based on class template parameter value根据类模板参数值禁用成员函数
【发布时间】:2020-04-28 20:00:47
【问题描述】:

我想要一个基于类的模板参数值禁用/启用成员函数的类。我有以下内容:

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 来决定返回类型或函数参数之一

【问题讨论】:

  • 基本上是的
  • 会有多少种不同的排列?对于像这样的 2 的简单示例,您可以只针对两个不同的选项专门化该类。
  • 只有两种类型,我之前已经实现过该解决方案,但其中有一些不同的功能。我希望我可以只上“一个”课
  • 您真正需要的是constexpr if,但这是 C++17 的特性。否则,您可以有多个重载并使用 SFINAE,例如刚刚回答的 jork。

标签: c++ c++11 templates metaprogramming enable-if


【解决方案1】:

如果我对您的理解正确,您将需要以下之一:

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> {
};

【讨论】:

  • 我不确定SomethingElse 的意图,所以考虑一下这个伪代码...
  • 所以我使用第一种方法得到以下编译错误:`error: need typename before std::enable_if 因为 std::enable_if 是一个依赖范围......有什么想法吗?
  • 是的,忘记了typename,正如错误所说...已修复:)
  • 是的,很抱歉,忘了那个小问题
  • 实际上,当我在 type1 对象上尝试此操作时,我收到以下错误:no type named 'type' in struct std::enable_if&lt;&gt; 有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 2023-03-23
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多