仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
Define conversion operator only for some template specializations: expected a type / expected type-specifier
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<>
。该类应将其声明为普通运算符方法。感谢伊戈尔·坦德特尼克发布的此链接。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- JS相等运算符(如===)是否可以使用embind类型
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 将所有模板类型传递给运算符,而不指定所有类型
- 标准库类型的赋值运算符的引用限定符
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 如何确保接受的C++模板类型使运算符重载?
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- 使用类型id运算符的最佳替代方法
- 为什么 std::make_shared 无法编译带有已删除运算符 new 的类型?
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 运算符'<'不能应用于类型 'string' 和 'string' 的操作数
- 为什么重载运算符可以返回其返回类型以外的其他内容?
- 表达式必须具有类类型(运算符)
- 使用许多类型运算符过载时,模棱两可的超载
- 类型转换为类型&&运算符
- 返回类型 ?:运算符和 C++ Primer 中的措辞
- 返回类型与返回类型(运算符++)不相同,也不协变