简体   繁体   中英

Scope resolution operator on object

In C++ we have an operator:: , which allows us to do things like that:

typedef std::pair<A, B> pairAB;
pairAB p;

pairAB::first_type a(42);
pairAB::second_type b("hello world");

p.first = a;
p.second = b;

I tried to use this operator on the object of this type:

pairAB p2;

p2::first_type a2(42);
p2::second_type b2("hello again");

p2.first = a2;
p2.second = b2;

And the compiler showed me error: C2510: 'p2' : left of '::' must be a class/struct/union , and I want to know is there any trick which allows me to do that?

If you are using GCC, there is a pre-C++11 equivalent called __typeof__ that behaves similarly. Try:

#include <string>

int main()
{
  typedef std::pair<int, std::string> pairAB;
  pairAB p2;

  __typeof__(p2.first) a2 = 42;
  __typeof__(p2.second) b2 = "hello again";

  p2.first = a2;
  p2.second = b2;
}

Example here.

Alternatively, if you can use boost , it provides Boost.typeof which should work in older Visual C++ compilers as well.

Getting the type of a variable is exactly what decltype keyword is for in c++11.

decltype(p2.first) a2 = 42;

Prior to c++11 there was no standard way to do that. There are compiler specific features such as gcc's typeof and library based implementations such as Boost.Typeof that have existed prior to c++11 and do a similar thing.

There's no need for C++11 features nor compiler extensions like typeof in C++03, which are not portable. If the variable is being used, its type is available somewhere -let's say it is T in a template or a function signature.

Then you can simply typename T::first_type since pair carries with itself member type information for its member types (as do many other STL classes such as containers, string , ...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM