为什么这段代码(一些模板的东西)在msvc10中编译得很好但是在gcc4.8.1中编译失败了?

时间:2013-12-05 16:16:29

标签: c++ templates

#include <iostream>
#include <typeinfo>
using namespace std;

struct mystruct{};

template<typename T>
struct map;

//specification
#define MAPPING(Key, Val)       \
template<>                      \
struct map<Key>                 \
{                               \
    typedef Val mapping_type;   \
};

MAPPING(mystruct, int)

template<typename T>
void func(T t)
{
    map<T>::mapping_type i = 999;
    cout<<i<<endl;
}


int main() {
    // your code goes here
    mystruct ms;
    func(ms);

    return 0;
}

我尝试通过规范做一些类型映射(这里映射mystruct到int),但它不能通过gcc4.8.1编译,帮助!

或者正确的方法是什么,谢谢!

http://ideone.com/yefbtk

以下是错误消息:

prog.cpp: In function ‘void func(T)’:
prog.cpp:23:2: error: need ‘typename’ before ‘map<T>::mapping_type’ because ‘map<T>’ is a dependent scope
  map<T>::mapping_type i = 999;
  ^
prog.cpp:23:23: error: expected ‘;’ before ‘i’
  map<T>::mapping_type i = 999;
                       ^
prog.cpp:24:8: error: ‘i’ was not declared in this scope
  cout<<i<<endl;
        ^
prog.cpp: In instantiation of ‘void func(T) [with T = mystruct]’:
prog.cpp:31:9:   required from here
prog.cpp:23:2: error: dependent-name ‘map<T>::mapping_type’ is parsed as a non-type, but instantiation yields a type
  map<T>::mapping_type i = 999;
  ^
prog.cpp:23:2: note: say ‘typename map<T>::mapping_type’ if a type is meant

1 个答案:

答案 0 :(得分:1)

正如Mat在评论中指出的那样,在使用map :: mapping_type之前必须包含typename。

template<typename T>
void func(T t)
{
    typename map<T>::mapping_type i = 999;
    cout<<i<<endl;
}