如何访问基类型定义
GCC: how to access base typedef?
我不能在gcc的简单代码中访问受保护的基类型typedef:
#include <iostream>
#include <memory>
#include <map>
template <class X>
X& Singleton()
{
static X x;
return x;
}
template<class GUID_T, class MAP_T, class T>
class TypeFactory {
protected:
bool ContainsInternal(MAP_T id) {
auto it = types.find(id);
return (it != types.end());
}
typedef GUID_T GUID;
inline virtual MAP_T GetTypeID(GUID guid) = 0;
std::map<MAP_T, T> types;
public :
void Add(GUID guid, const T & value) {
auto id = GetTypeID(guid);
if(!ContainsInternal(id)) {
types.insert(std::make_pair(id, T(value)));
}
}
bool Contains(GUID guid) {
return ContainsInternal(GetTypeID(guid));
}
std::shared_ptr<T> Get(GUID guid) {
auto id = GetTypeID(guid);
std::shared_ptr<T> result;
auto it = types.find(id);
if(it != types.end()) {
result = std::make_shared<T>(it->second);
}
return result;
}
std::map<MAP_T, T> & GetAll() {
return types;
}
};
template<class T>
class IntTypeFactory : public TypeFactory<int, int, T> {
protected:
inline virtual int GetTypeID(GUID guid) {
return guid;
}
};
class Type {
public: int a;
};
int main() {
IntTypeFactory<Type> & Types (Singleton< IntTypeFactory<Type> >());
IntTypeFactory<Type> & Types2 (Singleton< IntTypeFactory<Type> >());
auto t_in = Type();
t_in.a = 10;
Types.Add(1, t_in);
auto t_out = Types2.Get(1);
std::cout << t_out->a << std::endl;
return 0;
}
可以在VS2010中编译和工作。并为GCC工作,如果我从字面上声明inline virtual int GetTypeID(int guid) {
,那么我的GCC代码有什么问题,如何使它看到受保护的父类类型定义?
您必须限定GUID
类型名称。编译器不会在基类中查找非限定名,并且由于它在全局命名空间中既不可用,也不能作为IntTypeFactory
中的类型别名,因此它最终会抱怨GUID
是不存在的类型的名称:
template<class T>
class IntTypeFactory : public TypeFactory<int, int, T> {
protected:
inline virtual int GetTypeID(
typename TypeFactory<int, int, T>::GUID guid) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return guid;
}
};
MSVC不实现模板的两阶段查找,总是在实例化时查找名称,这就是为什么它在VS2010中编译。然而,这种行为不符合标准。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- 当基类是依赖类型时,这是一个缺陷吗
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 为什么允许dynamic_cast到非唯一的基类类型?
- 基类类型向量中的派生结构
- C++ 模板:重载时找不到基类类型参数方法
- 如果类包含基类类型的成员作为第一个元素,后跟其他成员,编译器是否可以优化空基?
- 如何在不转换回基类类型的情况下返回派生类型的对象?
- 声明基类类型的指针,但随后通过指向子类来实例化它.这是良好的编程实践吗?
- 获取继承基类类型的元组
- 如何从指针调用派生类函数到基类类型 (C++)
- 如何检查对象是否是基类类型
- 来自存储在带有基类类型的地图中的派生类的调用函数
- 采用基类类型参数的虚拟函数
- 用派生类填充基类类型的2D矢量
- 基类类型的指针忘记了原始对象类型
- 在c++中推回基类类型2d vector中的子类对象
- 子类对象,用作定义为c++基类类型的参数
- 从基类类型的向量访问派生类方法
- 从基类类型的指针数组调用派生类的方法.(c++)