【问题标题】:Deduced conflicting types without template推导出没有模板的冲突类型
【发布时间】:2020-09-03 20:02:52
【问题描述】:

我正在尝试创建一种可以存储 int、double 或 uint 的类型,如下所示:

struct Value
{
    /*...*/

    Value& operator=(const int value) { /*...*/ }
    Value& operator=(const double value) { /*...*/ }
    Value& operator=(const uint value) { /*...*/ }

    operator int() const { /*...*/ }
    operator double() const { /*...*/ }
    operator uint() const { /*...*/ }
}

当我尝试使用它时,我收到了关于“推断冲突类型”的错误。我在某处读到“演绎指南”可以提供帮助,但它似乎需要模板。我的类型不需要模板。

有没有一种解决方案可以使用这种 Value 类型,而无需每次都将其转换为 int、double 或 uint?

Value v;
v=123;

// I would like to type:
std::clamp(v,0,1234); // error

// But I need to type:
std::clamp(int(v),0,1234); // ok

操作员也有同样的问题(错误信息不同)

int x=v+12;

我认为我应该添加更多的运算符重载,但我没有找到哪个。

【问题讨论】:

    标签: operator-overloading c++17 type-deduction deduction-guide


    【解决方案1】:

    // 我想输入:

    std::clamp(v,0,1234); // error
    

    试试

     // .......VVVVV
     std::clamp<int>(v, 0, 1234);
    

    问题是std::clamp()的签名是

     template<class T>
     constexpr const T& clamp( const T& v, const T& lo, const T& hi );
    

    所以如果你在不解释T的情况下调用它,

     std::clamp(v, 0, 1234);
    

    模板类型T是从vint推导出来的Value,从01234推导出来的。

    考虑到冲突的类型,你会得到一个错误。

    如果你明确了模板类型

     // .......VVVVV
     std::clamp<int>(v, 0, 1234);
    

    没有更多的推论,编译器期望int在第一个位置,所以operator int ()v调用。

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多