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

问题描述 投票:0回答:1

我正在尝试模板,并且想知道是否有可能实现这样的目标:

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

此模板类将在基于给定数据的情况下使用其构造函数创建其自身的实例的地方,例如:

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.

这甚至可能吗?从我的研究中,我发现使用Variadic模板可以在C ++ 11中使用但不确定如何实现。

我正在尝试根据结构中的数据成员(在这种情况下,其字符串,整型和浮点数)创建该模板化类的实例,只要我们从其他类获取数据,只要它们与结构匹配。

非常感谢您的帮助!

c++ c++11 templates variadic-templates
1个回答
0
投票

如果我正确地理解了您(并且不确定我能做到),那么您可以执行以下操作:

#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 ();
}

输出:

14TemplatedClassINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEifE

但是必须固定模板化类中数据成员的数量。

Live demo

© www.soinside.com 2019 - 2024. All rights reserved.