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