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