4

In MSVC2010 The following code gives:
error C2039: 'my_type' : is not a member of ''global namespace''

template<typename T>
class C
{
public:
    typedef T my_type;
};

C<int> c;

auto f = [&c]() { 
    decltype(c)::my_type v2;   // ERROR C2039
};

I've found a lame way to work around it but I'm wondering what the proper way is to get at the typedef when you only have an object instance.

dwcanillas
  • 3,562
  • 2
  • 24
  • 33
tukra
  • 921
  • 8
  • 13
  • 2
    Upgrade your compiler version or rely or workarounds, one that comes to my mind is `identity::type::my_type v2;` with `template struct identity { typedef T type; };` – Piotr Skotnicki May 12 '15 at 19:13
  • Perfect, thanks! I wasn't sure if it was a VC2010 problem or me just not understanding what to do. – tukra May 12 '15 at 19:26
  • 1
    You don't need to capture `c` either (if it's global or static). – David G May 12 '15 at 19:29
  • 1
    Is `c` a `C` or a `C&` in the body of the lambda? While capturing a global variable is pointless, maybe the compiler is actually doing it? Try throwing in a decay or remove reference? – Yakk - Adam Nevraumont May 12 '15 at 19:41
  • @Yakk In the real code c is not a global or static. I get the same error with f = [c]() { ... } so that would be the same as ref removal right? – tukra May 12 '15 at 19:46
  • 1
    @tukra then `decltype(c)` would be `C&` no? And `C&::my_type` is not much sense (maybe it should work, but I could see a creaky compiler failing even if it should). Try `typename std::remove_reference::type::my_type`? – Yakk - Adam Nevraumont May 12 '15 at 19:47
  • @Yakk `decltype(c)` is `C` in [gcc and clang++](http://coliru.stacked-crooked.com/a/6e1aa1de91161c5a), though I don't know wich rule states so – Piotr Skotnicki May 12 '15 at 19:50
  • Turns out I need identity and ref removal. remove_reference does both jobs nicely. I posted an answer with a working solution. Thanks!!! – tukra May 12 '15 at 20:22
  • Verified that decltype(c) is C& in MSVC2010. Using type_name() from the second answer at [Print variable type in C++](http://stackoverflow.com/questions/81870/print-variable-type-in-c) – tukra May 12 '15 at 20:30

1 Answers1

1

From a conglomerate of very helpful comments I got a working solution. Thanks everyone. remove_reference serves dual purpose as an identity object.

template<typename T>
class C {
public:
  typedef T my_type;
};

void g() {
  C<int> c;

  auto f = [&c]() {
    typedef remove_reference<decltype(c)>::type::my_type my_type;
    my_type v;   // Works!!
  }; 
}
tukra
  • 921
  • 8
  • 13