简体   繁体   English

C++ - 可以返回不同类型的模板函数?

[英]C++ - Template function that can return different types?

I'm working on a section of code that allows the user to search by different types ( double / string / date (custom class)).我正在处理一段代码,允许用户按不同类型( double / string / date (自定义类))进行搜索。 This involves a method called readInSearchCriteria() that I have tried to set as a template.这涉及一个名为readInSearchCriteria()的方法,我试图将其设置为模板。 I have done some research into template functions and here is what I have so far:我已经对模板函数进行了一些研究,这是我目前所做的:

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

I have called this at one point in the program to process a double like so:我在程序中的某个时刻调用了它来处理像这样的double

double amount = theUI_.readInSearchCriteria<double>(); //works absolutely fine

However, when I tried to call it on a string , I was given the following error by the compiler:但是,当我尝试在string上调用它时,编译器给出了以下错误:

no suitable constructor exists to convert from "int" to "std::basic_string, std::allocator>"没有合适的构造函数可以将“int”转换为“std::basic_string, std::allocator>”

Would anyone be able to offer me any advice on what might be going wrong here?任何人都可以就这里可能出现的问题向我提供任何建议吗?

You have a typo in your function declaration: you're not specifying a return type, so the compiler is defaulting to int .您的函数声明中有一个错字:您没有指定返回类型,因此编译器默认为int

You need to add T as the return type:您需要添加T作为返回类型:

template <typename T>
T UserInterface::readInSearchCriteria() const {
    ...
    return T
}

The method readInSearchCriteria doesn't have a return type. readInSearchCriteria方法没有返回类型。 You have to specify the return type for a function, here it is implicit int because you haven't specified one.您必须为函数指定返回类型,这里是隐式int因为您尚未指定。

template <typename T> T UserInterface::readInSearchCriteria() const;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM