gpt4 book ai didi

c++ - 从 BoostCon 谈话中重载取消引用运算符的奇怪方式

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:08 24 4
gpt4 key购买 nike

我在 youtube 上观看了名为“现代 C++ 技术简介(第一部分)”的 boostcon 演讲。在第 22 分钟左右,演讲者展示了一个重载解引用运算符的类。

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_;
};

我从未见过这种重载取消引用运算符的方法。为什么没有返回类型,为什么 T 出现在“operator”关键字之后?我一直认为重载这个运算符的方式是这样的:

T& operator *()
{
// ...
return *value_
}

如果有人感兴趣,here is the talk

最佳答案

它是类型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-seqconversion-declaratoropt

conversion-declarator:

ptr-operator conversion-declaratoropt

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

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

关于c++ - 从 BoostCon 谈话中重载取消引用运算符的奇怪方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com