有什么方法可以根据类模板类型来初始化此变量? [英] Any way to initialize this variable based on class template type?
问题描述
我有一个带有模板的 stats
类,因此它可以很灵活.不过,我是模板的新手,我认为模板的目的是使模板在用户周围变得灵活.因此,当我碰到一堵小墙时,我感觉好像做错了事.
I have a class stats
with a template so that it can be flexible. I'm new to templates though, and I thought the point of them was to make it flexible around the user. So I feel like I'm doing something wrong seeing as I've hit a small wall.
#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 ++中有可能吗?
From int main()
, ideally, I'd like tmp to not have to be changed by myself every time I wan to try a different type. Is that possible in C++?
推荐答案
惯用的方法是公开类型别名:
The idiomatic way would be to expose a type alias:
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
的类型.
That way, tmp
will always take the type of T
.
要简化主要功能,也可以在其中使用别名:
To even simplify your main function, you can use an alias there too:
int main()
{
using stats_t = stats<std::string>;
stats_t s;
stats_t::value_type tmp;
while (std::cin >> tmp)
{
s.push(tmp);
}
// ...
}
这篇关于有什么方法可以根据类模板类型来初始化此变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!