Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 仅为某些模板专门化定义转换运算符:应为类型/应为类型说明符 模板 A类{}; 运算符A::bool(){ 返回true; } //目标: bool b1=A();//允许 //bool b2=A();//错误_C++_Template Meta Programming_Implicit Conversion_Template Specialization_Conversion Operator - Fatal编程技术网

C++ 仅为某些模板专门化定义转换运算符:应为类型/应为类型说明符 模板 A类{}; 运算符A::bool(){ 返回true; } //目标: bool b1=A();//允许 //bool b2=A();//错误

C++ 仅为某些模板专门化定义转换运算符:应为类型/应为类型说明符 模板 A类{}; 运算符A::bool(){ 返回true; } //目标: bool b1=A();//允许 //bool b2=A();//错误,c++,template-meta-programming,implicit-conversion,template-specialization,conversion-operator,C++,Template Meta Programming,Implicit Conversion,Template Specialization,Conversion Operator,CLion在第二个a上给出了错误“预期a类型”。GCC在A上给出错误“预期类型说明符”。当使用typename而不是int时,会出现类似的错误。为什么,以及如何仅为某些模板专门化定义转换 版本信息: C++20、CLion 2019.1.4、CMake 3.14.3、GCC 8.3.0、Debian 8.3.0-6我认为解决方案是将操作符关键字移动到双冒号后面:A::operator bool(),并在定义之前添加模板。类应将其声明为普通运算符方法。多亏了。您可以使用SFINAE实现以下目的:

CLion在第二个
a
上给出了错误“预期a类型”。GCC在
A
上给出错误“预期类型说明符”。当使用
typename
而不是
int
时,会出现类似的错误。为什么,以及如何仅为某些模板专门化定义转换

版本信息:
C++20、CLion 2019.1.4、CMake 3.14.3、GCC 8.3.0、Debian 8.3.0-6

我认为解决方案是将操作符关键字移动到双冒号后面:
A::operator bool()
,并在定义之前添加
模板。类应将其声明为普通运算符方法。多亏了。

您可以使用SFINAE实现以下目的:

template<int a>
class A {
public:
    template<int B = a, class = std::enable_if_t<B == 0>>
    operator bool() const {
        return true;
    }
};
模板
甲级{
公众:
样板
运算符bool()常量{
返回true;
}
};

<代码>此代码仅与C++类似。这没有什么意义,不清楚您想要实现什么。@IgorTandetnik我的用例是类型化单位,其中无单位值可以隐式转换为(或从)底层的
double
。(模板参数是单位类型的指数,因此
Value
应隐式转换为
double
,但其他
Value
应隐式转换)。您可能正在寻找@IgorTandetnik,谢谢!请随意写下您自己的答案和/或复制我的答案(无论是否给我评分)!