使用模板从函数返回不同的数据类型 [英] Returning a different data type from function using a template

查看:86
本文介绍了使用模板从函数返回不同的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个解析XML的函数,并使用模板返回 std :: string int .我想出了以下代码:

I am trying to create a function to parse XML and return either a std::string or int using templates. I have come up with the following code:

template <class T>
T queryXml(char *str)
{
     if (typeid(T) == typeid(int))
         return evalulate_number(doc);
     else
         return evaluate_string(doc);
}

...并像这样调用函数:

...and calling the function like this:

queryXml<int>("/people/name"); //I would like an int returned
queryXml<std::string>("/people/name"); //I would like a string returned

但是我收到错误消息,说不能将pugi :: string_t {aka std :: basic_string< char>}转换为int .有没有更好,更清洁的方式使用模板来执行此操作?谢谢!

But I get errors saying cannot convert pugi::string_t{aka std::basic_string<char>} to int in return. Is there a better and cleaner way to do this using templates? Thank you!

推荐答案

模板特化.

// The general form in your algorithm is to use a string...
template <class T>
T queryXml(char *str)
{
   return evaluate_string(doc);
}

// ...and you want special behavior when using an int
template <>
int queryXml(char *str)
{
   return evalulate_number(doc);
}

这篇关于使用模板从函数返回不同的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆