I have tried to use C++0x initializer list as argument to a constructor call in this way:
Foo<float> foo("Foo 1", std::vector<const char *>({ "foo A", "foo B" }) );
with the constructor
Foo(const char *name, std::vector<const char *> &foos)
With this constructor the compiler complained:
error: no matching function for call to Foo<float>::Foo(
const char [5], std::vector<const char *, std::allocator<const char *> >)
note: candidates are: Foo<T>::Foo(const char *, std::vector<const char *,
std::allocator<const char *> >&) [with T = float]
However, when I've changed the constructor to
Foo(const char *name, std::vector<const char *> foos)
Everything worked as expected. Why does the first constructor not work? I thought the vector could be constructed in the place of constructor call and passed down by reference, but obviously there's some problem. Could anybody explain that?
Thanks
Btw. I am using g++ version 4.4.5
EDIT: Thanks to the correct answers below, I have found also why I can't do that.
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .
initializer_list constructorsThe initializer_list Class represents a list of objects of a specified type that can be used in a constructor, and in other contexts. You can construct an initializer_list by using brace initialization: C++ Copy. initializer_list<int> int_list{5, 6, 7};
You cannot bind a temporary to a T&
.
You can bind a temporary to T const&
:
Foo(const char* name, std::vector<const char*> const& foos)
But I'd question the sanity of a vector
of char
pointers. What's wrong with std::string
?
Temporary cannot be bound to non-const reference, so do this:
Foo(const char *name, const std::vector<const char *> &foos)
//^^^^ note this
The initializer list is a red hering, I think. You are trying to bind a temporary to a non-const reference, which is illegal. Try using a const reference.
Foo(const char *name, std::vector<const char *> const& foos)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With