Accessing individual types of variadic templates

自作多情 提交于 2019-12-11 13:26:47

问题


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?


回答1:


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)... 
    };
}


来源:https://stackoverflow.com/questions/13444567/accessing-individual-types-of-variadic-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!