尝试支持文字时构造函数重载歧义

Constructor Overloading Ambiguity When Trying to Support Literals

代码

#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<Type>(Type & a) 适用于大多数情况。但是,它不适用于文字(例如 1.732)。这就是我添加 MyContainer<Type>(Type a) 的原因。但是,通过添加它,我最终会产生歧义,因为非文字可以使用任一构造函数。


问题

Is there a way to satisfy all parameters (both literal and non-literal) given to a constructor?

只需将值类型参数更改为 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"; }
                   // ^^^^^     ^
};