Template method specialization - what happened to my code?
What's wrong with this code?
class School {
public:
template<typename T> size_t count() const;
private:
vector<Boy*> boys;
vector<Girl*> girls;
};
template<> size_t School::count<Boy>() const {
return boys.size();
}
My compiler says
error: specialization of ‘size_t School::count() [with T = Boy]’
after instantiation
Could you help me?
ps. This is how I will use it later:
School s;
size_t c = s.count<Boy>();
+2
a source to share
3 answers
Did you accidentally call count<Boy>
in School
before his announcement? One way to reproduce your error is
class Boy;
class Girl;
class School {
public:
template<typename T> size_t count() const;
size_t count_boys() const { return count<Boy>(); }
// ^--- instantiation
private:
std::vector<Boy*> boys;
std::vector<Girl*> girls;
};
template<> size_t School::count<Boy>() const { return boys.size(); }
// ^--- specialization
int main () { School g; return 0; }
You need to move the definition count_boys()
after all members of the template are specialized.
+4
a source to share
This compiled code is compiled and run with g ++:
#include <vector>
using namespace std;
struct Boy {};
struct Girl {};
class School {
public:
template<typename T> size_t count() const;
private:
vector<Boy*> boys;
vector<Girl*> girls;
};
template<> size_t School::count<Boy>() const {
return boys.size();
}
int main() {
School s;
size_t c = s.count<Boy>();
}
In the future, please put more effort into posting compiled code - in other words, code with the required header files and supporting classes.
0
anon
a source
to share