OlegG
OlegG

Reputation: 1017

Why can't initialize my class from an initializer list even if it derives from std::list?

I have the following code.

#include <utility>
#include <list>
#include <iostream>

class Pair: public std::pair<unsigned int, unsigned int>{
    Pair (unsigned int h, unsigned int l) : pair(h,l){};
};
class PairList: public std::list<Pair>{};


int main(int argc, char** argv){

    PairList pl = {{800,400},{800,400}};
}

I compile it using MinGW g++ of v4.6 with the command line
g++ -std=c++0x Test.cpp -o test.exe
and got the error:
error: could not convert '{{800, 400}, {800, 400}}' from '<brace-enclosed initializer list>' to 'PairList'
But if in main() I write
list<pair<unsigned int,unsigned int>> pl = {{800,400},{800,400}};
all works fine.
WTF?

Upvotes: 1

Views: 193

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

There are two ways:

  1. Don't inherit the from the standard classes, use typedef instead:

    typedef std::pair<unsigned int, unsigned int> Pair;
    typedef std::list<Pair> PairList;
    
  2. Implement the correct constructors in your inherited classes (taking std::initializer_list as argument), the base class constructors can't be used automatically.

I recommend the first alternative, as the standard classes (with few exceptions) are not designed to be inherited.

Upvotes: 6

Related Questions