Home > database >  How to deduce template parameters based on return type?
How to deduce template parameters based on return type?

Time:10-24

I am attempting to create a simple 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.

#include <iostream>
using namespace std;

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

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

I have written the following simple code to solve the problem

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

    return _input;
}

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'

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>()?

I don't need a function template necessarily, any solution will do that lets the code in main work as written.

CodePudding user response:

Conversion operators can mimic that.

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;
   }
};

Mind however that this may not be applicable for every sort of operation. Plus, this is a fairly naive way of holding on the the prompt. You'd need to copy it proper if object lifetime issues become a concern.

  • Related