Search code examples
c++c++11templatesvariadic-templatesnon-type

How to resolve this issue with variadic non-type template parameter in C++11?


enum Enum
{
    e0,
    e1,
    e2
};

int translate(Enum e)
{
    //...
}

int translate(Enum e, int index)
{
    //...
}

class A
{
public:
    template<typename... Ts>
    A(Ts... ts)
    {
        //...
    }

};

template<Enum... es>
class B
{
public:
    static std::shared_ptr<A> getA()
    {
        //for example,use "int translate(Enum e)"
        //return std::make_shared<A>(translate(es)...);

        //use "int translate(Enum e, int index)"    "index" like the index in "for(int index = 0; index < n; ++index)"
        //how to writer?
    }
};

This is about variadic non-type template parameters; I want to use C++11 to resolve it.

For example:

std::make_shared<A>(translate(e1, 0), translate(e2, 1), translate(e3, 2))

std::make_shared<A>(translate(e1, 0), translate(e2, 1))

std::make_shared<A>(translate(e3, 0), translate(e0, 1))

Solution

  • Here's a solution using std::integer_sequence. It's a C++14 feature, but ports to C++11 do exist (haven't used this, can't vouch for its quality).

    template<Enum... es>
    class B
    {
      template <int... Is>
      static std::shared_ptr<A> getAHelper(std::integer_sequence<Is...>) {
        return std::make_shared<A>(translate(es, Is)...);
      }
    public:
        static std::shared_ptr<A> getA()
        {
          return getAHelper(std::make_integer_sequence<sizeof...(es)>{});
        }
    };