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

Define conversion operator only for some template specializations: expected a type / expected type-specifier

本文关键字:类型 运算符 说明符 转换 定义 专用      更新时间:2023-10-16
template<int a>
class A {};
operator A<0>::bool() {
    return true;
}
// Goal:
bool b1 = A<0>();   // Allow
//bool b2 = A<1>(); // Error

CLion 在第二个A上给出错误"预期类型"。GCC 在 A<0> 上给出错误"预期的类型说明符"。当使用typename而不是int时,这会产生类似的错误。为什么,以及如何只为某些模板专业化定义转换?

版本信息:

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

你可以使用 SFINAE 来实现这一点:

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

我认为解决方案是将运算符关键字移到双冒号之后:A<0>:: operator bool(),并在定义之前添加template<>。该类应将其声明为普通运算符方法。感谢伊戈尔·坦德特尼克发布的此链接。