Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;-可以返回不同类型的模板函数?_C++_Templates_Template Function - Fatal编程技术网

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;