1

我有以下模板化功能...

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 中可行吗?

更新:我目前正在使用 -pedantic 打开的 gcc 4.6。非编译器特定的解决方案将是首选。

4

1 回答 1

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

这将正确地转发引用,即使您的构造函数通过(常量或非)引用和其他值来获取它的一些参数。

于 2012-03-29T09:01:09.443 回答