std::make_shared with std::initializer_list

后端 未结 2 2006
死守一世寂寞
死守一世寂寞 2020-12-03 14:14
#include 
#include 

class Base
{
public:
    Base() {}
};

class Derived : public Base
{
public:
    Derived() {}
    Derived(std::ini         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 14:40

    For this to work, you need to create a custom make_shared_from_list, as make_shared does not support non-explicit initializer lists. The reason is described well by @brian.

    I would use a traits class to map a type T to the type of initializer list.

    templatestruct list_init{};// sfinae support
    template<> struct list_init{using type=std::pair>;};
    
    templateusing list_init_t=typename list_init::type;
    
    template
    std::shared_ptr make_shared_from_list( std::initializer_list> list ){
      return std::make_shared( std::move(list) );
    }
    

    or something like that.

    Alternatively, "cast" the {...} to the initializer_list directly (not a cast, but rather a construction) may work.

    In theory, sufficient reflection metaprogramming support would allow shared_ptr to do this without the traits class, bit that is pretty far down the pipe.

提交回复
热议问题