简体   繁体   English

对象的范围解析运算符

[英]Scope resolution operator on object

In C++ we have an operator:: , which allows us to do things like that:在 C++ 中,我们有一个operator:: ,它允许我们做这样的事情:

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?编译器向我显示了error: C2510: 'p2' : left of '::' must be a class/struct/union ,我想知道是否有任何技巧可以让我这样做?

If you are using GCC, there is a pre-C++11 equivalent called __typeof__ that behaves similarly.如果您使用 GCC,则有一个 C++11 之前的等效项__typeof__ ,其行为类似。 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.或者,如果您可以使用boost ,它会提供Boost.typeof ,它也应该适用于较旧的 Visual C++ 编译器。

Getting the type of a variable is exactly what decltype keyword is for in c++11.获取变量的类型正是 c++11 中decltype关键字的作用。

decltype(p2.first) a2 = 42;

Prior to c++11 there was no standard way to do that.在 c++11 之前,没有标准的方法来做到这一点。 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.有一些特定于编译器的功能,例如 gcc 的typeof和基于库的实现,例如 Boost.Typeof,它们在 c++11 之前就已经存在,并且可以做类似的事情。

There's no need for C++11 features nor compiler extensions like typeof in C++03, which are not portable.不需要 C++11 特性,也不需要像 C++03 中的typeof这样的编译器扩展,它们是不可移植的。 If the variable is being used, its type is available somewhere -let's say it is T in a template or a function signature.如果正在使用该变量,则其类型在某处可用 - 假设它是模板或函数签名中的 T。

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 , ...).然后你可以简单地typename T::first_type因为pair携带其成员类型的成员类型信息(就像许多其他 STL 类,如容器、 string等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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