2

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?

3
  • You can't use strings as template arguments. Commented Apr 28, 2012 at 15:55
  • Good point! I will correct the example. Commented Apr 28, 2012 at 16:07
  • @MiniKarol please look at my updated answer. The accepted answer is not as efficient or pretty as the updated one (thanks to Xeo). Commented Apr 28, 2012 at 17:09

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

8 Comments

This won't work as std::array does not have a constructor that accepts an std::initializer_list.
@n.m. oh, that seems weird. Why does array<int, 4> a { 1, 2, 3, 4 }; work then?
@Seth: Direct initialization, std::array is a POD type. You can use that same syntax in the member initializer btw.
@Xeo oh that explains it then, I didn't know array was POD. Thanks. What do you mean "you can use that same syntax in the member initializer"?
Thank it works perfectly but I have to enclose Args... within two pairs of brackets - MyClass(): array{{Args...}}{}
|
0
MyClass()
{
    std::initializer_list<MyEnum> il( {Args...} );
    std::copy (il.begin(), il.end(), array.begin());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.