奇怪的方式从BoostCon谈话过载解除引用操作符 [英] Strange way of overloading the dereference operator from a BoostCon talk

查看:145
本文介绍了奇怪的方式从BoostCon谈话过载解除引用操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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


类X的成员函数,没有带有

形式名的参数

conversion-function-id:



operator conversion-type-id



-id:



type-specifier-seq
conversion-declaratoropt



conversion-declarator: / p>

ptr-operator conversion-declaratoropt



指定从X转换为转换指定的类型-type-id 。这样的函数称为
转换函数。



如果转换函数是成员函数,转换函数(8.3.5)的
类型是function taken no parameter returning conversion-type-id


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

A member function of a class X having no parameters with a name of the form

conversion-function-id:

operator conversion-type-id

conversion-type-id:

type-specifier-seq conversion-declaratoropt

conversion-declarator:

ptr-operator conversion-declaratoropt

specifies a conversion from X to the type specified by the conversion-type-id. Such functions are called conversion functions. No return type can be specified.

If a conversion function is a member function, the type of the conversion function (8.3.5) is "function taking no parameter returning conversion-type-id".

这篇关于奇怪的方式从BoostCon谈话过载解除引用操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆