简体   繁体   中英

Accessing individual types of variadic templates

I am creating a lua binding in C++11. I want to process each type in a variadic template.

I was thinking I could do something like this, except using Params... represents all of the types inside of it, and not a the next single type inside of it like variadic function parameters do.

template <class T, typename ReturnType, typename... Params>
struct MemberFunctionWrapper <ReturnType (T::*) (Params...)>
{

    static int CFunctionWrapper (lua_State* luaState)
    {
        for(int i = 0; i < sizeof...(Params); i++)
        {
             //I want to get the next type, not all of the types
             CheckLuaValue<Params...>();
             //Do other stuff
        }
    }
};

How would I go about doing this?

You can do this by simply expanding after the function call, into something that can be expanded to.

// put this in your namespace
struct Lunch { template<typename ...T> Lunch(T...) {} }; 

// and this instead of the for loop
Lunch{ (CheckLuaValue<Params>(), void(), 0)... };

You can do something else with a lambda. You can even have your i incremented

static int CFunctionWrapper (lua_State* luaState)
{
    int i = 0;
    Lunch{ 
      (CheckLuaValue<Params>(), 
       [&]{ std::cout << "That was param " << i << std::endl; }(),
       ++i)... 
    };
}

Note that the Standard supports putting everything into the lambda. Compiler support until recently (last time I checked) wasn't very good though

static int CFunctionWrapper (lua_State* luaState)
{
    int i = 0;
    Lunch{([&]{ 
       CheckLuaValue<Params>();
       std::cout << "That was param " << i << std::endl;
    }(), ++i)... 
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM