gpt4 book ai didi

c++ - 有什么方法可以根据类模板类型初始化此变量?

转载 作者:行者123 更新时间:2023-12-02 09:47:47 25 4
gpt4 key购买 nike

我有一个带有模板的stats类,因此它可以很灵活。不过,我对模板还是陌生的,我认为它们的目的是使它在用户周围变得灵活。因此,当我碰到一堵小墙时,感觉好像做错了什么。

#include <iostream>
#include <cstdio>
#include <iomanip>

template <typename T>
class stats
{
private:
int n;
T sum;
public:
stats()
{
this->n = 0;
this->sum = T();
}
void push(T a);
void print();
};

int main()
{
std::string tmp; // change type based on class type T
stats<std::string> s;
while (std::cin >> tmp) // while input is active...
{
s.push(tmp);
}

// Output & Formatting
s.print();
return 0;
}
template <typename T>
void stats<T>::push(T a)
{
this->sum += a;
++this->n;
}
template <typename T>
void stats<T>::print()
{
std::cout << std::left << std::setw(4) << "N" << "= " << n << '\n'
<< std::left << std::setw(4) << "sum" << "= " << sum << '\n';
}
int main()出发,理想情况下,我希望每次尝试尝试其他类型时都不必自己更改tmp。在C++中有可能吗?

最佳答案

惯用的方式是公开类型别名:

template <typename T>
class stats
{
public:
using value_type = T;

// ...
};
然后在您的主要:
int main()
{
stats<std::string> s;
decltype(s)::value_type tmp;
while (std::cin >> tmp)
{
s.push(tmp);
}

// ...
}
这样, tmp将始终采用 T的类型。
为了简化您的主要功能,您也可以在其中使用别名:
int main()
{
using stats_t = stats<std::string>;
stats_t s;
stats_t::value_type tmp;
while (std::cin >> tmp)
{
s.push(tmp);
}

// ...
}

关于c++ - 有什么方法可以根据类模板类型初始化此变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63907609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com