简体   繁体   English

可以控制C ++中模板内的返回类型吗?

[英]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") 用法如下: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. 你可以返回一个封装所有可能的返回类型的类型(比如boost :: any或boost :: variant)。

You have to overload foo() ; 你必须重载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" );

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

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