0

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*>;
Triumphant
  • 948
  • 1
  • 11
  • 28
  • What problem are you seeing? – Vaughn Cato Sep 01 '14 at 03:06
  • It looks like you are trying to create an arbitrary instance of the `Ts` types, but I suspect you want real values. If the `Ts` are `const char *`, what do you want the string values to be? Having a more complete example of the problem (with a main) may make it more clear what you are trying to do. – Vaughn Cato Sep 01 '14 at 03:13
  • @VaughnCato, see this question I asked before, it contained the full context, http://stackoverflow.com/questions/25580294/c-11stdintegral-constantchar-kernel32-dll-wont-compile – Triumphant Sep 01 '14 at 03:17
  • Are you looking for something like this? http://ideone.com/4l4ekb – Vaughn Cato Sep 01 '14 at 03:27
  • @VaughnCato, 'constexpr' is not supported in VS 2013, thank you all the same – Triumphant Sep 01 '14 at 03:31
  • 1
    Ok, well that's not a big deal to work around: http://ideone.com/A0qdSW – Vaughn Cato Sep 01 '14 at 03:33

1 Answers1

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.

Pradhan
  • 16,391
  • 3
  • 44
  • 59