简体   繁体   中英

Can the return type inside templates in C++ be controlled?

I have a templated function similar to:

template<class T>
T foo( string sReturnType )
{
   //pseudo code
   if( sReturnType = "string" )
   {
        lookup data in string table
        return a string
   }
   else
   {
        look up in number table
        return number answer
    }


}

usage would be something like: foo("string")

inside the function, there needs to be logic that either pulls from a string table or a number table and returns that value. I played around with this and wasn't able to get it to work as I expected. It seems like it should be pretty straight forward and easy to do. Is this a valid approach and use of templates? I looked at template specialization but then you end up writing two separate code bases anyways, why not use an overloaded function? Is there a better way?

No - there is no way to declare a function having different return types (A template function may have different return types, but these would depend on a template parameter).

You could return a type encapsulating all possible return types (like boost::any or boost::variant) instead.

You have to overload foo() ; There's pretty much no way around it.

std::string foo( std::string )
{
    // look up data...
    return std::string();
}

int foo( int )
{
    // look up data...
    return -1;
}

int i = foo( 1 );
std::string s = foo( "string" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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