1

これについて質問したばかりですが、何が間違っているのか理解できません。小さな部分だけを書き直しましたが、エラーが見つかりません(親の戻り子でC ++関数を参照として使用)

私のコード:

#include <iostream>
#include <stdlib.h>
#include <cstring>

using namespace std;

template<class Derived>
class Entity {
    private:
        string _name;
    public:
        const string& name() const;
        Derived& name( const string& );
        Derived* This() { return static_cast<Derived*>(this); }
};

class Client : Entity<Client> {
    private:
        long int _range;
    public:
        const long int& range() const;
        Client& range( const long int& );
};

const string& Entity::name() const {
    return _name;
}

Derived& Entity::name(const string& name) {
    _name = name;
    return *This();
}

const long int& Client::range() const {
    return _range;
}

Client& Client::range( const long int& range ) {
    _range = range;
    return *this;
}

int main() {
    Client ().name("Buck").range(50);
    return 0;
}

結果:

untitled:25: error: ‘template<class Derived> class Entity’ used without template parameters
untitled:25: error: non-member function ‘const std::string& name()’ cannot have cv-qualifier
untitled: In function ‘const std::string& name()’:
untitled:26: error: ‘_name’ was not declared in this scope
untitled: At global scope:
untitled:29: error: expected constructor, destructor, or type conversion before ‘&amp;’ token
untitled: In function ‘int main()’:
untitled:13: error: ‘Derived& Entity<Derived>::name(const std::string&) [with Derived = Client]’ is inaccessible
untitled:44: error: within this context
untitled:44: error: ‘Entity<Client>’ is not an accessible base of ‘Client’

私は答えに非常に感謝します(私の無能は睡眠不足が原因かもしれませんが:D)

4

2 に答える 2

4

特殊な関数を次のように実装する必要があります。

template<>
const string& Entity<Client>::name() const {
    return _name;
}

template<>
Client& Entity<Client>::name(const string& name) {
    _name = name;
    return *This();
}

また、公開継承を追加します。

class Client : public Entity<Client>

にアクセスできますname()

一般的な実装が必要な場合:

template<class x>
const string& Entity<x>::name() const {
    return _name;
}

template<class x>
x& Entity<x>::name(const string& name) {
    _name = name;
    return *This();
}
于 2011-12-20T14:34:11.267 に答える
2

If you define members of a class template outside the template definition, then you need to include the template specification:

template <class Derived>
const string& Entity<Derived>::name() const {
    return _name;
}

template <class Derived>
Derived& Entity<Derived>::name(const string& name) {
    _name = name;
    return *This();
}

You also need to inherit publicly from Entity:

class Client : public Entity<Client> {
    // stuff
};
于 2011-12-20T14:37:40.217 に答える