访问各种类型的可变参数模板

sFu*_*ler 1 c++ variadic-templates c++11

我在C++ 11中创建了一个lua绑定.我想在可变参数模板中处理每种类型.

我想我可以做这样的事情,除了使用Params...代表它里面的所有类型,而不是像变量函数参数那样的内部的下一个单一类型.

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
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Joh*_*itb 6

您可以通过在函数调用之后简单地扩展到可以扩展到的内容来实现.

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

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

你可以用lambda做其他事情.你甚至可以i增加你的

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

请注意,标准支持将所有内容放入lambda.编译器支持直到最近(我上次检查)虽然不是很好

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