【问题标题】:Constructor Overloading Ambiguity When Trying to Support Literals尝试支持文字时构造函数重载歧义
【发布时间】:2016-11-02 19:10:20
【问题描述】:

代码

#include <iostream>

template <typename Type>
class MyContainer
{
private:
    Type contained;
public:
    MyContainer<Type>(Type & a): contained(a) { std::cout << "&\n"; }
    MyContainer<Type>(Type   a): contained(a) { std::cout << "_\n"; }
};

class Epidemic
{
private:
    int criticality;
public:
    Epidemic(int c): criticality(c);
};

int main()
{
    // using objects //
    Epidemic ignorance(10);
    MyContainer<Epidemic> testtube(ignorance); // should print "&"; error instead

    // using primitive //
    double irrationalnumber = 3.1415;
    MyContainer<double> blasphemousnumber(irrationalnumber); // should print "&"; error instead

    // using literal //
    MyContainer<double> digits(123456789.0); // prints "_"
}

说明

MyContainer&lt;Type&gt;(Type &amp; a) 适用于大多数情况。但是,它不适用于文字(例如1.732)。这就是我添加MyContainer&lt;Type&gt;(Type a) 的原因。但是,通过添加这个,我最终会产生歧义,因为非文字可以使用任一构造函数。


问题

有没有办法满足给构造函数的所有参数(文字和非文字)?

【问题讨论】:

  • MyContainer&lt;Type&gt;(const Type&amp; a) 代替值类型?
  • @πάνταῥεῖ & jrok -- 是的,谢谢你们!现在可以了。是因为在幕后,文字(在int 文字的情况下)是const ints?我想这很有道理。

标签: c++ class constructor overloading constructor-overloading


【解决方案1】:

只需将值类型参数更改为const 引用即可:

template <typename Type>
class MyContainer
{
private:
    Type contained;
public:
    MyContainer<Type>(Type & a): contained(a) { std::cout << "&\n"; }
    MyContainer<Type>(const Type& a): contained(a) { std::cout << "_\n"; }
                   // ^^^^^     ^
};

【讨论】:

  • 这是否也意味着我可以删除第一个构造函数(假设我没有更改构造函数中的参数)?
  • @SirJony 是的,只要您不想更改输入参数。我已经想知道你为什么要区分这些情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
相关资源
最近更新 更多