我有课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';
}
From 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);
}
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)