2

How do I need to define a constructor such that i can construct a class A like A({a,b,c}). This arised in an urge to avoid using a variadic constructor which seems dangerous.

Code:

#include <vector>

class A{
public:
A(const unsigned int a, const unsigned int b, const unsigned int c) /*: A({a,b,c})*/ {} 
A(const std::vector<unsigned int> v) {}
};


int main(){
A(1,2,3); //works
A({1,2,3}); // doesnt compile

return 0;
}

My aim is to construct a network with arbitrarily many hidden layers. The vector is supposed to contain the amount of nodes contained by the corresponding layer.

edit:

/home/simbla/qt_projects/minimalWorkingExample/main.cpp:158: error: call of overloaded 'A(<brace-enclosed initializer list>)' is ambiguous
 A({1,2,3});
          ^

Solution:

use std::initializer_list instead of std::vector

Gladaed
  • 211
  • 1
  • 8

3 Answers3

3

There's actually more constructors in your question than you let on. Here's two more, courtesy of your compiler:

A(A const&) = default;
A(A &&) = default;

Now the interesting bit is what happens when you write another initializer, A{1, 2, 3}. That calls your first user defined c'tor. Nothing novel there. But when you write A({1, 2, 3}), overload resolution has two options. Either construct a temporary A{1, 2, 3} and copy it. Or construct a vector for the other user provided c'tor.

In both cases it's a user defined conversion sequence. Neither is better than the other, so you get a nice flashing error due to ambiguity.

The solution? Either use brace initialization A{{1,2,3}}; or supply an initializer_list constructor, to better match the initializer list argument.


StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1
A(const std::vector<unsigned int> v) {}

No, vector is not the right thing. You want

A(const std::initializer_list<unsigned int> v) {}
iBug
  • 35,554
  • 7
  • 89
  • 134
1

I think you are looking for std::initializer_list:

struct S {
    std::vector<int> v;
    S(std::initializer_list<int> l) : v(l) {
        std::cout << "constructed with a " << l.size() << "-element list\n";
    }
};

int main() {
    S s({1, 2, 3, 4, 5});

}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58