c++ - GCC:如何访问基本类型定义?

标签 c++ visual-studio-2010 templates gcc c++11

我无法在 simple code in gcc: 上访问 protected 基类型 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 顺便说一句...如果我按字面声明 inline virtual int GetTypeID(int guid) { 那么适用于 GCC 那么我的 GCC 代码有什么问题如何让它看到 protected 父类 typedef?

最佳答案

您必须限定 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 进行编译。但是,此行为不符合标准。 GCC 是正确的。

关于c++ - GCC:如何访问基本类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097594/

相关文章:

visual-studio-2010 - 像在 AfterBuild 中一样实现 BeforePublish

C++:将 const 与模板参数组合

c++ - CppUnit,非常简单的测试代码崩溃了,为什么?

c# - 退出 C# winforms 应用程序

c++ - 我的程序的独特行为,无法识别

javascript - VS 2010 Javascript 匹配大括号/括号突出显示

c++ - 如何使模板类的一个实例与同一模板的另一个实例成为 friend

c++ - 模板和语法

c++ - 标准 C++ 字符串库的奇怪行为

c++ - 使用 BSTR 数据类型时出错