gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:03:17 24 4
gpt4 key购买 nike

我想要一个类,它根据类的模板参数的值禁用/启用成员函数。我有以下几点:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com