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
答案 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。