Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my template accept an initializer list

Tags:

I have created a template as follows

template<typename T> void f(T const& t) { } 

I wanted for this to be callable by containers but also by initializer lists. I thought it would be initializer_list<int>, when called as follows.

f({1, 2, 3}); 

But GCC behaves as if it's not Standards compliant

m.cpp: In function 'int main()': m.cpp:6:25: warning: deducing 'const T' as 'const std::initializer_list<int>' m.cpp:4:6: warning:   in call to 'void f(const T&) [with T = std::initializer_list<int>]' m.cpp:6:25: warning:   (you can disable this with -fno-deduce-init-list) 

Can anyone explain how I can make this work without warnings? Thanks!

like image 990
Johannes Schaub - litb Avatar asked Jan 21 '11 10:01

Johannes Schaub - litb


People also ask

How do I use initializer list?

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.

When must you use a member initializer list?

Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

Does initializer list call constructor?

An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.

What is initializer in Dev C++?

An initializer specifies the initial value of a variable. You can initialize variables in these contexts: In the definition of a variable: C++ Copy. int i = 3; Point p1{ 1, 2 };


1 Answers

A "thing" like {1,2,3} does not qualify as an expression. It has no type. Therefore, no type deduction is done. But C++0x makes an explicit exception for 'auto', so

auto x = {1,2,3}; 

actually works and decltype(x) will be initializer_list<int>. But this is a special rule that only applies to auto. I guess they wanted to make loops like these

for (int x : {2,3,5,7,11}) {    ... } 

work since this kind of loop exploits the special rule.

As for solving the problem, you could add an initializer_list<T> overload as a "wrapper":

template<class T> inline void outer(initializer_list<T> il) {    inner(il); } 

I didn't test this but my current understanding is that it should work.

like image 94
sellibitze Avatar answered Oct 24 '22 08:10

sellibitze