Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++0x initializer list passed by reference

Tags:

c++

c++11

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.

like image 964
Radim Vansa Avatar asked Jun 10 '11 10:06

Radim Vansa


People also ask

How do you initialize a list in C++?

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.

What is std :: initializer_list?

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 .

What is braced init list in C++?

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};


3 Answers

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?

like image 64
Lightness Races in Orbit Avatar answered Oct 20 '22 21:10

Lightness Races in Orbit


Temporary cannot be bound to non-const reference, so do this:

Foo(const char *name, const std::vector<const char *> &foos)
                    //^^^^ note this
like image 44
Nawaz Avatar answered Oct 20 '22 20:10

Nawaz


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)
like image 2
tokage Avatar answered Oct 20 '22 20:10

tokage