C++ C++;-可以返回不同类型的模板函数?
我正在编写一段代码,允许用户按不同类型进行搜索(C++ C++;-可以返回不同类型的模板函数?,c++,templates,template-function,C++,Templates,Template Function,我正在编写一段代码,允许用户按不同类型进行搜索(double/string/date(自定义类))。这涉及一个名为readInSearchCriteria()的方法,我已尝试将其设置为模板。我对模板函数做了一些研究,以下是我迄今为止所做的: //template function to process different datatypes template <typename T> UserInterface::readInSearchCriteria() const {
double
/string
/date
(自定义类))。这涉及一个名为readInSearchCriteria()
的方法,我已尝试将其设置为模板。我对模板函数做了一些研究,以下是我迄今为止所做的:
//template function to process different datatypes
template <typename T> UserInterface::readInSearchCriteria() const {
//template instance to hold data input from keyboard
T t;
//prompt user to enter a value
cout << "\n ENTER SEARCH CRITERIA: ";
//read-in value assigned to template variable
cin >> t;
//return initialised template variable
return t;
}
但是,当我试图在字符串上调用它时,编译器给了我以下错误:
没有合适的构造函数将“int”转换为“std::basic\u string,std::allocator>”
有谁能就这里可能出现的问题向我提供一些建议吗?您的函数声明中有一个输入错误:您没有指定返回类型,因此编译器默认为int
您需要添加T
作为返回类型:
template <typename T>
T UserInterface::readInSearchCriteria() const {
...
return T
}
模板
T UserInterface::readInSearchCriteria()常量{
...
返回T
}
方法readInSearchCriteria
没有返回类型。您必须为函数指定返回类型,这里它是隐式的int
,因为您没有指定返回类型
template <typename T> T UserInterface::readInSearchCriteria() const;
template T UserInterface::readInSearchCriteria()常量;
该代码中的返回类型在哪里?是否缺少T
?返回值在哪里?这不应该是t型的吗?我现在想起来了,这很符合逻辑。谢谢谢谢你的回复,真的很有帮助!
template <typename T> T UserInterface::readInSearchCriteria() const;