1
#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;
}

I try to do some type mapping(here mapping mystruct to int) via specification, but it can't compiled by gcc4.8.1, help!

or what is the right way to accomplish this, thanks!

http://ideone.com/yefbtk

Here are the error messages:

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
cyber4ron
  • 438
  • 5
  • 7
  • 7
    `error: need ‘typename’ before ‘map::mapping_type’ because ‘map’ is a dependent scope` - that's pretty explicit. Why don't you try that? – Mat Dec 05 '13 at 16:20
  • Because `msvc10` does not follow Standard unlike `gcc`. `gcc` is correct, you do need `typename` there. – lapk Dec 05 '13 at 16:22
  • sorry, it just work well after ‘typename’ added. didn't catch the error messages.. – cyber4ron Dec 05 '13 at 16:27
  • agree with mike, the error is because mcvc take map::mapping_type as a type not a data member by default, but gcc need to define that explicitly – cyber4ron Dec 05 '13 at 17:01

1 Answers1

1

As Mat pointed out in the comments, you must include typename before using map::mapping_type.

template<typename T>
void func(T t)
{
    typename map<T>::mapping_type i = 999;
    cout<<i<<endl;
}
flumpb
  • 1,561
  • 1
  • 14
  • 31