繁体   English   中英

在某些情况下,将auto用作返回类型和返回值nullptr

[英]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.

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