简体   繁体   English

如何从 function 返回类型推断 function 模板参数?

[英]how to deduce function template argument from function return type?

Example:例子:

template<typename T>
T get() {
    return T{};
}

void test() {
    float f = get();//requires template argument; e.g. get<float>();
}

I understand that float can be converted to double or even int ;我知道float可以转换为double甚至int is it possible to have get<T> instanciated automatically based on the requested return type?是否可以根据请求的返回类型自动实例化get<T> If so how?如果是这样怎么办?

No, template argument deduction from the return type works only for conversion operator templates:不,从返回类型中推导模板参数仅适用于转换运算符模板:

struct A {
    template<typename T>
    operator T() {
        //...
    }
};

//...

// calls `operator T()` with `T == float` to convert the `A` temporary to `float`
float f = A{};

This can also be used to have get return the A object so that float f = get();这也可以用来让get返回A object 以便float f = get(); syntax will work as well.语法也可以。 However, it is questionable whether using this mechanism as you intent is a good idea.但是,按您的意图使用此机制是否是个好主意值得怀疑。 There are quite a few caveats and can easily become difficult to follow.有很多注意事项,很容易变得难以遵循。 For example what happens in auto f = get();例如auto f = get();中发生了什么? What happens if there are multiple overloads of a function g in a call g(get()) ?如果在调用g(get())中多次重载 function g会怎样? Etc.等等。

Instead move your type specifier to the template argument and you wont have to repeat yourself:而是将您的类型说明符移动到模板参数,您将不必重复自己:

auto f = get<float>();

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

相关问题 从 std::function 的返回类型推导出模板参数 - Deduce template-argument from std::function's return type 如何推断模板中函数的返回类型 - how to deduce the return type of a function in template 如何“帮助”编译器从作为函数的模板参数中推断出函数模板的返回类型? - How to 'help' the compiler to deduce function template return type from a template parameter which is a function? 如何基于“类似于函数”参数推导函数模板的返回类型? - How to deduce the return type of a function template base on a “function like” parameter? 推导函数参数化的模板中的参数类型 - Deduce argument type in template parametrized by function GCC无法从模板函数推断出自动返回类型吗? - GCC cannot deduce auto return type from a template function? 在实例化之前推断出 function 模板的返回类型 - deduce return type of function template before instantiation 如何使模板推导出具有可变参数的函数返回类型 - How to make template deduce return type of function with variadic arguments 如何在函数重载中推导出 lambda 的模板参数? - How to deduce template argument for lambda, in function overload? 无法推断出作为函数的模板参数 - Cannot deduce template argument that is a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM