[英]Using auto as return type and return value nullptr in some cases
如果我们具有返回类型为auto
的方法,但是在该方法中,我们将返回一个新对象或nullptr
。 如果我正确理解何时返回nullptr
,它将通过构造函数创建新对象。
方法With
。
接下来的问题是:将使用哪种类型代替auto
? 这将取决于类型通过返回maybe
与否: maybe
是返回的函数Maybe<T>
当我们第一次调用With
返回类型为Maybe< Adress >
; 第二步,可能是Maybe< Adress >
因为它是对象的类型,或者Maybe< std::string >
-如果context不是nullptr
则返回。
struct Address {
string* house_name = nullptr;
};
struct Person {
Address* address = nullptr;
};
template <typename T> struct Maybe;
template <typename T> Maybe<T> maybe(T* context)
{
return Maybe<T>(context);
}
template <typename T>
struct Maybe {
T* context;
Maybe(T *context) : context(context) { }
template <typename TFunc>
auto With(TFunc evaluator)
{
return context != nullptr ? maybe(evaluator(context)) : nullptr;
}
};
...
void print_house_name(Person* p)
{
auto z = maybe(p)
.With([](auto x) { return x->address; })
.With([](auto x) { return x->house_name; })
.Do([](auto x) { cout << *x << endl; });
}
int main()
{
//print_house_name(nullptr);
Person p;
print_house_name(&p); // nothing
}
哪种类型将代替
auto
?
函数的返回类型由单个return
语句中的表达式类型决定。 您的情况是:
return context != nullptr ? maybe(evaluator(context)) : nullptr;
返回的表达式是一个三元运算符,其两个潜在值具有不同的类型( Maybe<C>
,对于某些类C
不一定是T
,并且为nullptr_t
)。 仅当其中一种类型可以隐式转换为另一种类型时,这种格式才正确。 通常, nullptr_t
仅与其他指针类型进行转换,因此让我们看一下为Maybe
定义的隐式转换(只有一个):
Maybe(T *context) : context(context) { }
指针类型可以转换为Maybe
。 因此,将nullptr
转换为C*
,然后将其转换为Maybe<C>
对象(其上下文为null)。 同样,我使用C
而不是T
因为此类型不必是*this
类型的一部分的同一模板参数。 无论context
的值如何,返回的类型都是相同的。
如果您希望看到这种隐式转换中断,请像explicit Maybe(T *context) : context(context) { }
一样,将转换转换为Maybe
。
auto
不是魔术。 它只是一个占位符,您的编译器将其填充为具体的推断类型。 最终结果与您手动编写推断类型完全相同 。
“如果我正确理解何时返回nullptr,它将通过构造函数创建新对象”。 否。返回nullptr
不会调用任何构造函数。 它只是返回适当类型的空值。 没有构造对象。
“哪种类型将代替汽车” -返回TUPE将是什么的你实际上会返回类型 。 那只能是一种特定的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.