我有以下模板化功能......
template< class T > T *create_object( lua_State *L )
{
// Get a raw block of memory, managed by Lua.
void *mem = lua_newuserdata( L, sizeof( T ) );
// Construct the object in the allocated memory.
T *object = new (mem) T;
// Do other stuff here...
return object;
}
...分配并设置一个C ++对象,以便在Lua脚本语言中使用。我想扩展这个函数,所以我可以传入对象的构造函数的参数。它可能看起来像这样:
template< class T > T *create_object( lua_State *L, ??? ctor_args )
{
void *mem = lua_newuserdata( L, sizeof( T ) );
T *object = new (mem) T( ctor_args ); // Call correct constructor as determined by args.
// ...
return object;
}
......并且做这样的事情:
class widget
{
public:
// Multiple constructors
widget(); // #1
widget( const widget &w ); // #2
widget( int width, int height, float x, float y ); //#3
};
class font
{
public:
font( std::vector<uint8_t> );
}
// Other classes with multiple constructors.
// Example usage: (L = lua_State pointer)
create_object<widget>( L ); // Pass no arguments - use constructor #1
create_object<widget>( L, existing_widget ); // Pass one argument- use constructor #2
create_object<widget>( L, 128, 64, 100.0f, 100.0f ); // Pass 4 arguments - use construct #3
create_object<font>( L, buffer ); // Just to show it needs to work with many object types...
... and so on ...
避免使用最终结果的可变参数模板:
create_object<widget, int, int, float, float >( L, 256, 512, 120.0f, 0.0f );
会很好。
这在c ++ 11中是否可行?
更新:我正在使用gcc 4.6并启用-pedantic。非编译器特定的解决方案将是首选。
答案 0 :(得分:9)
像这样,只要您对可变参数模板有适当的支持:
template< class T, typename... Args >
T *create_object( lua_State *L, Args&&... args)
{
void *mem = lua_newuserdata( L, sizeof( T ) );
T *object = new (mem) T(std::forward<Args>(args)...);
// ...
return object;
}
这将正确转发引用,即使你的构造函数通过(const或not)引用和其他值引用它的一些参数。