Search code examples
c++templatesc++11variadic-templates

C++ index of type during variadic template expansion


I have a simple yet daunting problem I can't solve by myself. I have something like

template<class T, class... Args>
T* create(SomeCastableType* args, size_t numArgs)
{
  return new T(static_cast<Args>(args[INDEX_OF_EXPANSION])...);
}

Suppose SomeCastableType is castable to any type. Obviously what I can't get is that INDEX_OF_EXPANSION.

Thank you very much for your help.


Solution

  • Indices trick, yay~

    template<class T, class... Args, std::size_t... Is>
    T* create(U* p, indices<Is...>){
      return new T(static_cast<Args>(p[Is])...);
    }
    
    template<class T, class... Args>
    T* create(U* p, std::size_t num_args){
      assert(num_args == sizeof...(Args));
      return create<T, Args...>(p, build_indices<sizeof...(Args)>{});
    }
    

    Of course, I strongly advise using a smart pointer and a std::vector instead of raw pointers.