开发者

Specialization of template method - what's wrong with 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 compile says

error: specialization of ‘size_t School::count() [with T = Boy]’
after instantiation

Could you please help?

ps. This is how I'm going to use it later:

School s;
size_t c = s.count<Boy>();


You are missing a semi-colon.

class School {
public:
    template<typename T> size_t count() const;
private:
    vector<Boy*> boys;
    vector<Girl*> girls;
};                           // <-- Missing semi-colon
template<> size_t School::count<Boy>() const {
    return boys.size();
}


Have you accidentally called count<Boy> in School before it is declared? 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 of count_boys() after all template members are specialized.


This compilable code compiles and runs OK 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 future, please make more effort to post compilable code - in other words, code with the necessary header files and supporting classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜