2016-03-15 21 views
4

有人可以告訴我爲什麼以下代碼在Visual Studio 2010中完美工作,但無法在gcc 5.3中編譯,儘管它看起來沒有什麼問題? 我已經做了一些Google搜索,但沒有找到描述模板類繼承的標準方法。類模板繼承無法在GCC中編譯,但在Visual Studio中工作

#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; 
} 
在視覺工作室

,它導致:

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)) ===| 

回答

6

問題是在兩階段查找,這是在GCC實現/鏗鏘聲,並沒有在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

相關問題