【问题标题】:How to make a template class object as a tuple?如何将模板类对象作为元组?
【发布时间】:2021-07-26 03:01:12
【问题描述】:
class Farmacie
{
    string proprietar;
    string denumire;
    int angajati;
    vector<int>profit;
    public:
        Farmacie(){}
};
class Farmacie_online:public Farmacie
{
    string proprietar;
    string web;
    int nr_vizitatori;
    int discount;
    public:
        Farmacie_online(){}
        Farmacie_online(string a,string b,int c, int d){
            this->proprietar=a;
            this->web=b;
            this->nr_vizitatori=c;
            this->discount=d;
        }
};
template <typename T,typename ...rest>
class GestionareFarmacii
{
    static int index;
    int id;
    T* date;
    public:
        GestionareFarmacii(int nr, int id){this->id=id;this->date=new T[nr];}
        GestionareFarmacii operator+=(const Farmacie_online& f)
        {
            this->date[index].first=f.web;
            this->date[index].second=f.nr_vizitatori;
            this->date[index].third=f.discount;
            index++;
            return *this;
        }

};
int main()
{
    Farmacie_online f("blabla","www.fs",25,50);
    GestionareFarmacii <tuple<string,int,int>>farm(10,23);
    farm+=f;
}

我无法从互联网上得到它应该如何使用这些东西,必须使用类,并且模板中的 id 只是整个模板的常量。我知道 += 是非常错误的,我不知道该怎么做,我试图展示我想要做的基本上,将farmacie_online 对象添加到模板对象数组中

【问题讨论】:

  • 我试图理解“如何将模板类对象作为元组制作?”是什么意思,但代码对我没有帮助。你是在说std::tuple吗?
  • 所以基本上我需要 main() 中的代码才能工作,比如有多个 farmacie_online 对象并制作 GestionareFarmacii &lt;tuple&lt;string,int,int&gt;&gt;farm(10,23); 这样的东西,然后将一些 farmacie_online 对象添加到 @ 987654328@
  • 它必须是向量类型>
  • 为什么要在模板中使用tuple?好像你正试图让你的 date 成为 tuple&lt;string, int, int&gt;
  • 好吧,我没看到那条线。所以,T = tuple&lt;string,int,int&gt;rest... 是空的。

标签: c++ class templates


【解决方案1】:

std::tuple 没有像 .first.second 这样的访问器。相反,您需要使用 std::get&lt;INDEX&gt;(yourTuple) 来访问每个元素。

如果你想单独分配每个项目,你可以这样做:

std::get<0>(date[index]) = f.web;
std::get<1>(date[index]) = f.nr_vizitatori;
std::get<2>(date[index]) = f.discount;

或者,您也可以使用 std::make_tuple 和您的值创建一个元组对象:

date[index] = std::make_tuple(f.web, f.nr_vizitatori, f.discount)

旁注,您可以将模板设置为:

template<typename ...T>
class GF
{
    ⋮
    tuple<T...>* date;
    ⋮
    GF(int nr, int id)
    {
        ⋮
        date = new tuple<T...>[nr];
    }
    ⋮
}

在你的主要,你可以将它作为GF&lt;string, int, int&gt; farm(10 ,23)

【讨论】:

  • 我强烈建议不要在这里(或任何地方)使用原始指针。元组向量会更安全、更易于使用。
  • @Kyle 我也同意。我只使用原始指针,因为 op 有,他的问题是关于使用 tuple 和“如何制作模板......”
猜你喜欢
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多