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

时间:2012-11-18 21:05:22

标签: c++ c++11 variadic-templates

我在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
        }
    }
};

我将如何做到这一点?

1 个答案:

答案 0 :(得分: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)... };

你可以用lambda做其他事情。您甚至可以增加i

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

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

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