【问题标题】:Various errors with CRTP (C++)CRTP (C++) 的各种错误
【发布时间】:2011-12-20 22:42:06
【问题描述】:

我知道我刚刚就这个问题提出了一个问题,但我无法弄清楚我做错了什么。我只重写了一小部分,找不到任何错误(使用C++ function in parent return child作为参考)

我的代码:

#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 ‘&’ 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)

【问题讨论】:

  • 如果代码不是很长,你应该把代码直接放在问题中。

标签: c++ crtp


【解决方案1】:

您需要像这样实现您的专门功能:

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();
}

【讨论】:

  • 非常感谢,现在编译。
  • 这只会为Client创建特化;您可能想要定义泛型函数,假设您希望多个类从 Entity 继承。
  • @MikeSeymour 我添加了通用实现。
【解决方案2】:

如果你在模板定义之外定义类模板的成员,那么你需要包含模板规范:

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();
}

你还需要从Entity公开继承:

class Client : public Entity<Client> {
    // stuff
};

【讨论】:

    猜你喜欢
    • 2011-02-27
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多