仅为某些模板专业定义转换运算符:预期类型/预期类型说明符

时间:2019-07-20 03:16:29

标签: c++ template-meta-programming implicit-conversion template-specialization conversion-operator

template<int a>
class A {};
operator A<0>::bool() {
    return true;
}

// Goal:
bool b1 = A<0>();   // Allow
//bool b2 = A<1>(); // Error

CLion在第二个A上给出错误“ Expected a type”。 GCC在A<0>上给出错误“ expected type-specifier”。当使用typename而不是int时,这会产生类似的错误。为什么,为什么我只能为某些模板专业化定义转换?

版本信息:

C ++ 20,CLion 2019.1.4,CMake 3.14.3,GCC 8.3.0,Debian 8.3.0-6

2 个答案:

答案 0 :(得分:1)

您可以为此使用SFINAE:

template<int a>
class A {
public:
    template<int B = a, class = std::enable_if_t<B == 0>>
    operator bool() const {
        return true;
    }
};

答案 1 :(得分:0)

我认为解决方案是将operator关键字移动到双冒号A<0>:: operator bool()之后,并在定义之前添加template<>。该类应将其声明为常规运算符方法。感谢this link posted by Igor Tandetnik