【问题标题】:Class template inheritance fails to compile in GCC but works in Visual Studio类模板继承无法在 GCC 中编译,但在 Visual Studio 中有效
【发布时间】:2016-03-15 09:58:46
【问题描述】:

有人能告诉我为什么以下代码在 Visual Studio 2010 中完美运行,但在 gcc 5.3 中编译失败,尽管它似乎没有任何问题? 我已经进行了一些谷歌搜索,但没有找到描述模板类继承的清晰标准方法。

#include <iostream>
#include <string>

namespace foobar
{
    template <typename Char_Type = char>
    class basic_foo
    {
    public:
        inline basic_foo(){}
        virtual ~basic_foo(){}

        typedef std::basic_string< Char_Type > str_foo;
        enum { fooEnum = 100 };
    };

    template <typename Char_Type = char>
    class basic_bar :private basic_foo <Char_Type>
    {
    public:
        basic_bar(){}
        ~basic_bar(){}

        str_foo bar1()
        {
            int i = fooEnum;
            return str_foo("test succeeded\n");
        }
    };
}

typedef foobar::basic_bar<> bar2;

int main()
{
    bar2 bar;
    std::cout << bar.bar1();
    return 0;
}

在 Visual Studio 中,结果为:

test succeeded

但在 gcc 中,它说:

main.cpp|24|error: unknown type name 'str_foo'
main.cpp|26|error: use of undeclared identifier 'fooEnum'
main.cpp|27|error: use of undeclared identifier 'str_foo'
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    问题是两阶段查找,在gcc/clang中实现,VS中没有实现。

    您的代码应在标准需要的地方使用typenamethis

    template <typename Char_Type = char>
    class basic_bar :private basic_foo <Char_Type>
    {
    public:
        basic_bar(){}
        ~basic_bar(){}
    
        typename basic_foo<Char_Type>::str_foo bar1()
        {
            int i = this->fooEnum;
            return typename basic_foo<Char_Type>::str_foo("test succeeded\n");
        }
    };
    

    live example

    你可以阅读Where and why do I have to put the "template" and "typename" keywords?Two phase lookup - explanation needed

    【讨论】:

      猜你喜欢
      • 2019-03-21
      • 2012-11-30
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多