我試圖input()在 C 中創建一個類似于 Python的簡單函式。我希望代碼(下面)會提示用戶輸入他們的年齡,然后將其列印到控制臺中。
#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按撰寫的方式作業。
uj5u.com熱心網友回復:
轉換運算子可以模仿這一點。
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. 如果物件生命周期問題成為一個問題,您需要正確復制它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333138.html
下一篇:復制建構式在cpp模板中不起作用
