Search code examples
c++templatestypesvariadic-templates

C++ function : Variadic templates with no arguments


I am not sure if this question is already answered. But here it goes:

I was wondering if it's possible to do something like

template<typename...classes>
void createObject(){

  //pass each type into my template function wich takes one type only.

}

I'm really not getting how it exactly works. The reason I can't provide any function arguments is because my template function which should be called within the method only takes one type. This is because it returns an object depending on it's type.

Any suggestion?

Note: GCC 4.6.2


Solution

  • template<typename...>
    struct caller;
    
    template<typename T, typename...Rest>
    struct caller<T, Rest...>
    {
         static void call()
         {
            create<T>();
            caller<Rest...>::call();
         }
    };
    
    template<>
    struct caller<>
    {
         static void call()
         {
         }
    };
    
    //since you've not mentioned the return type, I'm assuming it to be void
    //if it is not void, then I don't know what you're going to return, and HOW!   
    template<typename...classes>
    void createObject(){
          caller<classes...>::call();
    }
    

    Demo : http://ideone.com/UHY8n


    Alternative (a shorter version):

    template<typename...>
    struct typelist{};
    
    template<typename T, typename ... Rest>
    void call(typelist<T,Rest...>)
    {
      create<T>();
      call(typelist<Rest...>());
    };
    
    void call(typelist<>) { }
    
    template<typename...classes>
    void createObject(){
          call(typelist<classes...>());
    }
    

    Demo : http://ideone.com/cuhBh