问题描述
我在YouTube上观看了一个boostcon演讲,题为现代C ++技术介绍(第一部分)。在分钟22,演讲者显示一个重载解引用操作符的类。
模板< typename T,
typename CheckingPolicy = NoChecking,
typename BadPointerPolicy = BadPointerDoNothing>
class pointer_wrapper
{
public:
pointer_wrapper():value_(0){}
explicit pointer_wrapper(T * p):value_(p){}
operator T *()
{
if(!CheckingPolicy :: check_pointer(value_))
{
return BadPointerPolicy :: handle_bad_pointer(value_);
}
else
{
return value_;
}
}
private:
T * value_;
};
我从来没有见过这种重载解引用操作符的方法。为什么没有返回类型,为什么T出现在'operator'关键字后面?
我一直认为重载这个操作符的方法是这样的:
operator *()
{
// ...
return * value_
}
如果有人感兴趣,请
这是隐式转换操作符类型T *
。
n3337 12.3.2 / 1
I was watching a boostcon talk on youtube titled "Introduction to Modern C++ Techniques (Part I)". Around minute 22 the speaker shows a class which overloads the dereference operator.
template<typename T,
typename CheckingPolicy = NoChecking,
typename BadPointerPolicy = BadPointerDoNothing>
class pointer_wrapper
{
public:
pointer_wrapper() : value_(0) {}
explicit pointer_wrapper(T* p) : value_(p) {}
operator T*()
{
if ( ! CheckingPolicy::check_pointer(value_) )
{
return BadPointerPolicy::handle_bad_pointer(value_);
}
else
{
return value_;
}
}
private:
T* value_;
};
I have never seen this way of overloading the dereference operator. Why is there no return type and why does the T appear after the 'operator' keyword?I always thought the way to overload this operator was like this:
T& operator *()
{
// ...
return *value_
}
If anybody is interested, here is the talk
It's implicit conversion operator to type T*
.n3337 12.3.2/1
这篇关于奇怪的方式从BoostCon谈话过载解除引用操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!