简体   繁体   中英

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?

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 (takingstd::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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM