如何从函数返回类型推导函数模板参数?

Pin*_*tle 0 c++ c++17

例子:

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

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

据我所知,float可以转换为doubleint;是否可以get<T>根据请求的返回类型自动实例化?如果是这样怎么办?

use*_*522 8

不,从返回类型推导模板参数仅适用于转换运算符模板:

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

//...

// calls `operator T()` with `T == float` to convert the `A` temporary to `float`
float f = A{};
Run Code Online (Sandbox Code Playgroud)

这也可以用于get返回A对象,以便float f = get();语法也可以工作。然而,按照您的意图使用这种机制是否是一个好主意是值得怀疑的。有很多警告,很容易变得难以遵循。例如发生了什么auto f = get();?如果g调用中某个函数多次重载会发生什么情况g(get())?ETC。

相反,将类型说明符移至模板参数,您不必重复自己:

auto f = get<float>();
Run Code Online (Sandbox Code Playgroud)