我有以下模板化函数...
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。非特定于编译器的解决方案将是首选。
最佳答案
像这样,前提是您对可变参数模板有适当的支持:
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 或非)引用获取它的一些参数,而其他参数通过值获取。
关于c++ - 如何创建一个带有可变数量参数的模板函数,将参数传递给对象的正确构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922129/