Fine Man
Fine Man

Reputation: 465

Constructor Overloading Ambiguity When Trying to Support Literals

Code

#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 "_"
}

Description

MyContainer<Type>(Type & a) is meant for most everything. However, it won't work with literals (e.g. 1.732). That's why I added a MyContainer<Type>(Type a). However, by adding this, I end up with an ambiguity because non-literals can use either constructor.


Question

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

Upvotes: 1

Views: 48

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Just change from the value type parameter to a const reference:

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"; }
                   // ^^^^^     ^
};

Upvotes: 2

Related Questions