CRTP (c++)的各种错误
Various errors with CRTP (C++)
我知道我刚才问了一个问题,但我不知道我做错了什么。我只重写了一小部分,找不到任何错误(使用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 ‘&’ 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)
您需要这样实现您的专用函数:
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();
}
如果您在模板定义之外定义类模板的成员,那么您需要包含模板规范:
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
};
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'