How to automatically deduce template parameters of type T for function of return type T (in C++)?

  c++, template-argument-deduction, templates

I am attempting to create a simpe input() function in C++ similarly to Python. I expected the code (below) to prompt the user for their age, then to print it into the console. Instead it gives me the following error message:

 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'

I have written the following simple code:

#include <iostream>
using namespace std;

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

    return _input;
}

int main(void)
{
    int age;
    age = input("How old are you? ");

    cout << "nYou are " << age << endl;
}

How do I make it so that input() automatically detects the fact that age is an int, and that I don’t have to write input<int>()?

Source: Windows Questions C++

LEAVE A COMMENT