简体   繁体   English

C ++ 14中的返回类型推导

[英]Return type deduction in C++14 in assignment

I was wondering whether a return type deduction in an assignment is possible in C++14 in some way. 我想知道在C ++ 14中以某种方式是否可以在赋值中进行返回类型推导。 It feels redundant to type the <int> after the return_five function name. return_five函数名称后键入<int>感觉很多余。 Thus, in other words, can the compiler use information from the left hand side of the assignment? 因此,换句话说,编译器可以使用分配左侧的信息吗?

#include <iostream>
#include <string>

template<typename T>
auto return_five()
{
    return static_cast<T>(5);
}

int main()
{
    int five_int = return_five();         // THIS DOES NOT WORK
    // int five_int = return_five<int>(); // THIS WORKS

    std::cout << "Five_int = " << five_int << std::endl;

    return 0;
}

C++ ain't VBA: the thing on the left hand side of the assignment is not used to deduce the type of the right hand side. C ++不是VBA:赋值左侧的内容用于推断右侧的类型

So the compiler requires an explicit type for return_five() . 因此,编译器需要return_five()的显式类型。 You inform the compiler of the type by writing return_five<int>() . 您可以通过编写return_five<int>()告知编译器类型。

Nope, but this is the best you can do: 不,但这是您可以做的最好的事情:

int main() {
  auto five_int = return_five<int>();
  // ...
}

It's not so much return type deduction as it is templating the return type: 它并没有像模板化返回类型那样大量的返回类型推导:

template<typename T>
T return_five()
{
    return 5;
}

This is not possible. 这是不可能的。 Template parameters of functions are only deduced from function arguments, not from return types (unfortunately). 函数的模板参数仅从函数参数推导出,而不是从返回类型推导出(不幸的是)。

Possibly not of much interest to you, but a way to deduce the template parameters is the following: 可能您不太感兴趣,但是可以通过以下方法推断模板参数:

template<typename T>
void return_five(T& value)
{
    value = static_cast<T>(5);
}

...

int five_int;
return_five(five_int);

Well, this works : 好吧,这可行:

struct return_five {
    template <class T>
    operator T() const { return 5; }
};

int main (int, char**) {
    int five_int = return_five();

    std::cout << five_int << '\n';
}

Hint : you probably don't want to actually use that in production code. 提示:您可能不想在生产代码中实际使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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