2012-11-18 31 views
1

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

我该怎么做呢?

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

注意,该标准支持把一切到拉姆达。编译器支持直到最近(我上次检查)不是很好,虽然

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

功能参数评估没有指定顺序,这不是UB吗?我会使用一个(临时)数组:'alias {(...,++ i)...}'。 – Xeo

+1

@Xeo它不是UB:当使用'{...}'时,即使它导致函数调用,也会定义顺序。请注意,当“Params”为空时(请求的数组大小为零),您的提案将失败。 –

+0

啊,很高兴知道。在扩展之前,通过设置一个虚拟的'0'可以很容易地解决零个案例。 – Xeo