Visual Studio gives an error regarding ambiguous ctor

I am stuck with compiler errors in VS 2013, where my custom class has an ambiguity error, but it works without ambiguity for std::vector

#include <initializer_list>
#include <vector>

using namespace std;

class MyArray
{
public:
    std::vector< int > values;
    MyArray(int s) : values(s) { }
    MyArray(std::initializer_list< int >list) { values = list; }
};

int main ()
{
    vector<int> vx({9,8,7}); // Works
    MyArray mx({9, 8, 7});   // Works

    vector<int> vy({9});     // Works
    MyArray my({9});         // VS-compiler complains about ambiguity
    MyArray mz(std::initializer_list<int>{9}); // Works
}

Of course, I can correct the ambiguity by adding the type explicitly: MyArray my(std::initializer_list<int>{9})but this is very inconvenient. Is there a way to code constructors so that VS doesn't complain about ambiguity for my class?

Since it std::vectordoes not give errors of ambiguity, it would seem that this should be possible.

+4
source share
2 answers

Try using std :: size_t in another constructor

, size_t ... , .

#include <initializer_list>
#include <vector>

using namespace std;

class MyArray
{
public:
    std::vector< int > values;
    MyArray(std::size_t s) : values(s) { }
    MyArray(std::initializer_list<int> list): values(list)
    {}
};

int main()
{
    int s({ 9 });
    vector<int> vx({ 9, 8, 7 }); // Works
    MyArray mx({ 9, 8, 7 });   // Works

    vector<int> vy({ 9 });     // Works
    MyArray my1(0);
    MyArray my({ 9 });         // VS-compiler complains about ambiguity
}
+2

, MS V++ 2013.

++ (13.3.1.7 , . # 1)

- - (8.5.4) T .

- , , T .

, .

, GCC.

Microsoft. . MS .

+4

All Articles