【发布时间】:2023-03-27 00:15:01
【问题描述】:
我模仿std::enable_shared_from_this创建了一个模板类,但是我让这个类在它的子类中使用了类型定义。
很遗憾!
虽然我用的是typename,但是编译后,
//
// https://ideone.com/eYCBHW http://ideone.com/eYCBHW
#include <iostream>
#include <set>
#include <map>
using namespace std;
template<class _S> struct A {
};
template<class _Subclass>
class Global {
public:
typedef typename _Subclass::connection_t connection_t;
//std::map<std::string, _Subclass::connection_t> connections;
//std::set<_Subclass::connection_t> connections;
//using typename _Subclass::connection_t;
//typename _Subclass::connection_t* connections;
//connection_t* connections;
};
class CConnection {};
class SConnection;
class Client : public Global<Client> {
public:
typedef CConnection connection_t;
};
#if 0
class Server : public Global<Server> {
public:
typedef SConnection connection_t;
};
#endif
class SConnection {};
int main() {
// your code goes here
return 0;
}
GCC 投诉:
prog.cpp: In instantiation of ‘class Global<Client>’:
prog.cpp:25:23: required from here
prog.cpp:14:43: error: invalid use of incomplete type ‘class Client’
typedef typename _Subclass::connection_t connection_t;
^~~~~~~~~~~~
prog.cpp:25:7: note: forward declaration of ‘class Client’
class Client : public Global<Client> {
^~~~~~
如何解决?
参考文献
【问题讨论】:
-
请注意,以下划线开头后跟一个大写字母(
_S、_Subclass!)的标识符以及包含两个后续下划线的标识符是为实现(即编译器)保留的。 -
不幸的是,C++ 不能以这种方式工作。在首先定义其超类之前,无法定义一个类。因此,您不能使用 CRTP 设计模式从超类引用子类中定义的内容。没有解决办法。你必须以某种方式重组事物。
-
你能解释一下你想要达到的目标吗?从代码中我不清楚...从我收集的信息来看,您想要的是 CRTP...
-
@SamVarshavchik 您可以从父类中引用子类中定义的内容,这就是 CRTP 的重点。但你只能在超类成员函数中做到这一点。
-
template<class Subclass, class Connection> class Global怎么样?