C++ 如何使用模板类创建其他类的实例?

C++ 如何使用模板类创建其他类的实例?,c++,c++11,templates,variadic-templates,C++,C++11,Templates,Variadic Templates,我正在尝试使用模板,并想知道是否有可能实现以下目标: template<typename T> class TemplatedClass{ private: T n; T z; T x; public: TemplatedClass(T n, T z, T x) { this->n= n; this->z= z; this->x= x; } #include <

我正在尝试使用模板,并想知道是否有可能实现以下目标:

template<typename T> class TemplatedClass{

private:
    T n;
    T z;
    T x;


public:

    TemplatedClass(T n, T z, T x) {
        this->n= n;
        this->z= z;
        this->x= x;
    }

#include <iostream>
#include <string>
#include <typeinfo>

template<typename T1, typename T2, typename T3> class TemplatedClass
{
private:
    T1 n;
    T2 z;
    T3 x;
};

struct Mystruct
{
    std::string n;
    int x;
    float d;
};

int main ()
{
    auto tc = TemplatedClass <decltype (std::declval <Mystruct> ().n),
                              decltype (std::declval <Mystruct> ().x),
                              decltype (std::declval <Mystruct> ().d)> {};
    std::cout << typeid (tc).name ();
}
模板类TemplatedClass{
私人:
T n;
tz;
tx;
公众:
模板类(tn,tz,tx){
这个->n=n;
这个->z=z;
这个->x=x;
}
其中,该模板类将基于给定数据使用其构造函数创建自身的实例,如:

struct Mystruct{
    string n;
    int x;
    float d;

};


void TemplatedClass<T>::createInstances(T o){
   TemplatedClass<Mystruct> tc(o.getS(), sizeof(o), 16.2f);
}
//Where (T o) is any other class that contains some function that returns a string.

struct Mystruct{
字符串n;
int x;
浮动d;
};
void TemplatedClass::createInstances(TO){
TemplatedClass tc(o.getS(),sizeof(o),16.2f);
}
//其中(to)是包含返回字符串的函数的任何其他类。
这可能吗?从我的研究中,我发现C++11可以使用可变模板 但不确定如何实施


我试图基于结构中的数据成员创建模板类的实例,在本例中,它的字符串、int和float,我们从其他类获取数据,只要它们与结构匹配


非常感谢您的帮助!

如果我理解正确(我不确定我是否理解),那么您可以这样做:

template<typename T> class TemplatedClass{

private:
    T n;
    T z;
    T x;


public:

    TemplatedClass(T n, T z, T x) {
        this->n= n;
        this->z= z;
        this->x= x;
    }

#include <iostream>
#include <string>
#include <typeinfo>

template<typename T1, typename T2, typename T3> class TemplatedClass
{
private:
    T1 n;
    T2 z;
    T3 x;
};

struct Mystruct
{
    std::string n;
    int x;
    float d;
};

int main ()
{
    auto tc = TemplatedClass <decltype (std::declval <Mystruct> ().n),
                              decltype (std::declval <Mystruct> ().x),
                              decltype (std::declval <Mystruct> ().d)> {};
    std::cout << typeid (tc).name ();
}
但是模板类中的数据成员数量必须是固定的


TemplatedClass
有三个类型为
Mystruct
的成员,其构造函数接受三个类型为
Mystruct
的参数。不是
字符串
int
浮点
。不清楚您试图实现什么。非常非常非常不清楚。我正在尝试创建该类的实例基于结构中的任何数据成员的类,在本例中,它的字符串、int和一个float,我们从其他类获取数据,只要它们与结构匹配。它们都必须具有MyStruct类型,不是吗?您是否尝试使用相同的参数?有什么意义?你会使用
TemplatedClass
做什么,而不能直接使用
Mystruct
?与其描述你提出的解决方案,不如描述你试图解决的原始问题。谢谢你的回答!在该模板类中使用构造函数可以吗?对不起,我很抱歉不明白。也许你可以在你的问题中添加一个你想做什么的例子。但是没有理由不让模板类有构造函数,如果你是这个意思的话。