how to construct class whose constructor function might have multiple parameter or none in template?

只谈情不闲聊 提交于 2019-12-25 11:05:42

问题


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: When I try to write such code, it won't compile:

adapter<const char*, const char*>;

回答1:


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

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



来源:https://stackoverflow.com/questions/25598265/how-to-construct-class-whose-constructor-function-might-have-multiple-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!