如何使用可变数量的参数创建一个模板化函数,将参数传递给对象的正确构造函数?

x-x*_*x-x 1 c++ lua templates variadic c++11

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

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;
}
Run Code Online (Sandbox Code Playgroud)

...分配并设置一个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;
}
Run Code Online (Sandbox Code Playgroud)

......并且做这样的事情:

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 ...
Run Code Online (Sandbox Code Playgroud)

避免使用最终结果如下的可变参数模板:

create_object<widget, int, int, float, float >( L, 256, 512, 120.0f, 0.0f );
Run Code Online (Sandbox Code Playgroud)

会好的.

在c ++ 11中这可能吗?

更新:我正在使用gcc 4.6并启用-pedantic.非编译器特定的解决方案将是首选.

Ale*_* C. 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;
}
Run Code Online (Sandbox Code Playgroud)

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