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

How to deduce template parameters based on return type?

我正尝试在 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() 自动检测到年龄是一个整数这一事实,而我不必写 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 的方式。如果对象生命周期问题成为一个问题,您需要正确复制它。