如何构造类的构造函数可能有多个参数或在模板中没有? [英] how to construct class whose constructor function might have multiple parameter or none in template?

查看:313
本文介绍了如何构造类的构造函数可能有多个参数或在模板中没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我想写一个可以实例类的通用模板,当然,这些类可能没有或有多个参数。所以模板必须有可变参数。任何人都可以帮助我?

Now I want to write a general template which can instance class, of course, these classes might have none or multiple parameters. So the template must have variadic arguments. Anybody can help me?

为了更好地理解我自己,请看下面的简单代码片段,我不知道如何使它工作:

To better make myself understood, please see the follwong simple code snippet, I don't know how to make it work:

class Print
{
public:
    Print(const char* param, const char* param2)
        : m_str1(param)
        , m_str2(param2)
    {}
    void outPut()
    {
        std::cout << m_str1 << "\t" << m_str2 << std::endl;
    }
private:
    std::string m_str1;
    std::string m_str2;
};

template<typename ... Ts>
struct adapter
{
    static void invoke()
    {
        C t((Ts::value)...); // make a instance on the fly
    }
};

update:
当我尝试编写这样的代码时,它不会编译:

update: When I try to write such code, it won't compile:

adapter<const char*, const char*>;


推荐答案

您正在寻找这样的东西:

You are looking for something like this:

template<typename T>
struct adapter
{
    template<typename ... Ts>
    static T invoke(Ts&& ... ts)
    {
        return T(std::forward<Ts>(ts)...); // make a instance on the fly
    }
};

要创建 T 您将使用适当的参数调用 adapter< T> :: invoke

To create an object of type T, you would call adapter<T>::invoke with the appropriate arguments.

这篇关于如何构造类的构造函数可能有多个参数或在模板中没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆