Std :: initializer_list as template argument for constructor

I have a class that inherits from the std container. I now have a template constructor that calls the base container constructor. this template constructor works for simple copying and moving the constructor, but not for initializer_list.

template<typename container_T>
class test : public container_T {
public:
  using container_type = container_T;

  test() {} 

  // templated constructor
  template<typename T>
  test(T t)
    : container_T(t) {}

   // without this it won't compile
  test(std::initializer_list<typename container_T::value_type> l)
    : container_T(l) {}
};

int main() {    
  test<std::deque<int>> vdi1;
  test<std::deque<int>> vdi2({1,2,3,4,5,6,7,8,9});

  std::cout << "vdi2 before:" << std::endl;
  for(auto it : vdi2)
    std::cout << it << std::endl;

  test<std::deque<int>> vdi3(std::move(vdi2));

  std::cout << "vdi2 before:" << std::endl;
  for(auto it : vdi2)
    std::cout << it << std::endl;

  std::cout << "vdi3 before:" << std::endl;
  for(auto it : vdi3)
    std::cout << it << std::endl;

  return 0;
}

if I remove the constructor initializer_list vdi2, it will not compile. now my question is: why is initializer_list not output by the template constructor? and can this be done?

+4
source share
1 answer

why initializer_list is not displayed by the constructor template?

, {1,2,3,4,5,6,7,8,9} - , . T .

std::initializer_list<T> ( ) T int. , .

auto x = {1,2,3,4,5,6,7,8,9};

x std::initializer_list<int>. , , . , , , , {1,2,3,4,5,6,7,8,9} , . ( T = int std::initializer_list<T>.) ( ) x std::initializer_list<int>. , , , x std::initializer_list<int>.

, DyP , , , ( , ) . , , , test:

using container_type::container_type;
+5

All Articles