简体   繁体   English

C ++中模板中的运算符重载

[英]Operator overloading in template in C++

I read following code from somewhere: 我从某处阅读以下代码:

template<class T> class A {
    T a;
public:
    A(T x):a(x) {}
    operator T() const {return a;}   // what is point here?
};


int _tmain(int argc, _TCHAR* argv[])
{
    A<int> a = A<int>(5);
    int n = a;
    cout << n;
    return 0;
}

What does below line mean? 下面的线是什么意思?

operator T() const {return a;} 运算符T()const {返回a;}

operator T() const {return a;} 运算符T()const {返回a;}

This is the typecast operator . 这是类型转换运算符 It'll implicitly convert the class instance to T . 它将隐式将类实例转换为T In the example code you've posted this conversion is being performed at the line 在您发布的示例代码中,此转换是在该行执行的

int n = a; int n = a;

It means if you want to convert an instance into a T you can use this operator, which here returns a copy of the private member. 这意味着如果要将实例转换为T ,则可以使用此运算符,该运算符将返回private成员的副本。

In your example code that is how you can assign a , which is of type A<int> to an int directly. 在示例代码中,可以直接将类型为A<int> a分配给int Try removing the operator T() and see how that fails to compile, with an error about assigining A<T> to an int . 尝试删除operator T() ,看看它如何编译失败,并出现关于将A<T>辅助到int的错误。

With the non explicit constructor (the opposite of marking a constructor explicit ) there too it makes this type behave a lot like the template type itself in a number of circumstances. 使用非explicit构造器(将构造器标记为explicit的相反),在许多情况下,它也使此类型的行为与模板类型本身非常相似。 In effect you've wrapped a T inside another class that behaves like a T when it needs to. 实际上,您已将T包裹在另一个类中,该类在需要时的行为类似于T You could extend this to do other, more useful things like monitoring/logging/restricting the use of real instances by hiding them behind something which controlled them. 您可以将其扩展为做其他更有用的事情,例如通过将真实实例隐藏在控制它们的东西后面来监视/记录/限制实际实例的使用。

Also notice how you can change A<int> a = A<int>(5); 还要注意如何更改A<int> a = A<int>(5); to simply A<int> a = 5; 简单地说A<int> a = 5; because of the implicit constructor. 由于隐式构造函数。

It's basically making a functor - which is an object with function semantics. 它基本上是在制造函子-这是具有函数语义的对象。 That means you can call the object just like a function as a replacement in places where you may have used a function - its a generic programming concept. 这意味着您可以像调用函数一样在代替函数的地方调用对象-它是通用的编程概念。

It's beneficial because you can have multiple instances of that function-object (functor) and they can each maintain their own state, where as if you had a straight-up function then it could only maintain state via static variables, and it would thus not be re-entrant (you only ever get one instance of a static variable). 这是有益的,因为您可以具有该功能对象(functor)的多个实例,并且每个实例都可以维护自己的状态,就好像您拥有一个简单函数一样,它只能通过静态变量维护状态,因此不会重入(只能获得一个静态变量的实例)。

Functors are heavily used in STL algorithms as an extra optional parameter. 在STL算法中,函子作为额外的可选参数被大量使用。

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

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