可能重复: Where and why do I have to put the “template” and “typename” keywords?
几周前,我(不得不:)成为了一名C++开发人员(我以前有过一些经验,但不是太多,我更擅长于Java),我试着学习所有重要的东西,并尽可能高效地开发。所以,如果我的问题是完全愚蠢的,请原谅。对于一个简单的模板类,我有一个问题:
template<typename T>
class SameCounter {
private:
map<T,int> counted;
public:
SameCounter(list<T> setup) {
for(list<T>::iterator it = setup.begin(); it != setup.end(); it++) {
counted[*it]++;
}
}
map<T,int>::const_iterator& begin() { // line 25
return counted.begin();
}
map<T,int>::const_iterator& end() {
return counted.end();
}
};
...
// using the class
Reader rdr;
rdr.Read();
SameCounter<char> sc(rdr.GetData());
我在编译它时遇到了一些错误:
Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int d:\learn_cpp\examples\gyakorlas_1.cpp 25
Error 2 error C2143: syntax error : missing ';' before '&' d:\learn_cpp\examples\gyakorlas_vizsga\gyakorlas_1.cpp 25
(both of them twice)
我对此没有头绪,我假设的模板可能有问题,因为如果我将SameCounter创建为一个正常的类,那就完全没有问题了。谢谢你的帮助。
发布于 2013-01-10 01:17:34
我已经注意到你下面的班了。有几点值得一提:
template<typename T>
class SameCounter
{
private:
typedef map<T,int> MapType; // typedef here to keep specific container in a single place
typedef typename MapType::const_iterator const_iterator; // to avoid retyping "typename"
typedef typename MapType::iterator iterator; // to avoid retyping typename
MapType counted;
public:
SameCounter(list<T> setup) {
// auto here to avoid complicated expression
for(auto it = setup.begin(); it != setup.end(); it++) {
counted[*it]++;
}
}
// by value instead of by reference, mark as const member
const_iterator begin() const {
return counted.begin();
}
// by value instead of by reference, mark as const member
const_iterator end() const {
return counted.end();
}
// probably best to also forward cbegin()/cend() and non-const begin() / end()
};
map
更改为另一个容器(例如,unorderd_map
),就会派上用场。它们避免重复键入嵌套类型的typename
。通常,最好使用与正在包装的函数相同的接口(一致性,返回值)(在本例中,映射的begin()/end() )。
https://stackoverflow.com/questions/14254134
复制