类模板继承无法在GCC中编译,但在Visual Studio中有效

时间:2016-03-15 09:58:47

标签: c++ templates inheritance

有人可以告诉我为什么以下代码在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)) ===|

1 个答案:

答案 0 :(得分:6)

问题在于两阶段查找,它在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

相关问题