如何根据返回类型推断模板参数?



我试图在c++中创建一个类似于Python的简单input()函数。我期望下面的代码提示用户输入他们的年龄,然后将其打印到控制台中。

#include <iostream>
using namespace std;
int main(void)
{
int age;
age = input("How old are you? ");
cout << "nYou are " << age << endl;
}

我写了下面的简单代码来解决这个问题

template <typename T>
T input(const string &prompt)
{
T _input;
cout << prompt;
cin >> _input;
return _input;
}

相反,它给了我以下错误消息:

In function 'int main()':
17:36: error: no matching function for call to 'input(const char [18])'
17:36: note: candidate is:
5:3: note: template<class T> T input(const string&)
5:3: note:   template argument deduction/substitution failed:
17:36: note:   couldn't deduce template parameter 'T'

我如何使input()自动检测age是int的事实,而我不必写input<int>()?

我不需要一个函数模板,任何解决方案都可以让main中的代码像写的那样工作。

转换操作符可以模拟。

struct input {
const string &prompt;
input(const string &prompt) : prompt(prompt) {}

template <typename T>
operator T() const {
T _input;
cout << prompt;
cin >> _input;
return _input;
}
};
但请注意,这可能不适用于所有类型的操作。另外,这是一种相当幼稚的持有prompt的方式。如果存在对象生命周期问题,则需要适当地复制它。