Create std::array from variadic template

混江龙づ霸主 提交于 2019-12-11 02:24:14

问题


I'd like to achieve something like that:

#include <string>
#include <array>

enum class MyEnum{
  A,
  B,
  C
};

template<MyEnum... Args>   
class MyClass{
  public:
    MyClass()
    {
    }
  private:
    std::array<MyEnum, sizeof...(Args)> array;   
};

Now I have an array, which can hold all passed to template values. But how can I populate this array with template parameters?


回答1:


If what you are wanting is to put all the MyEnum values into array, then you can unpack them into an initialiser list and initialise array with it initialise it with direct initialisation:

MyClass() : array {{ Args... }} { }

You need a fairly new compiler to use this syntax, however.

Thanks to Xeo for correcting my answer.




回答2:


MyClass()
{
    std::initializer_list<MyEnum> il( {Args...} );
    std::copy (il.begin(), il.end(), array.begin());
}


来源:https://stackoverflow.com/questions/10364874/create-stdarray-from-variadic-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!