如何为具有特定类型特征的所有类型编写函数模板?
考虑以下示例:
struct Scanner
{
template <typename T>
T get();
};
template <>
string Scanner::get()
{
return string("string");
}
template <>
int Scanner::get()
{
return 10;
}
int main()
{
Scanner scanner;
string s = scanner.get<string>();
int i = scanner.get<int>();
}
Scanner
类用于从某些源中提取令牌。上面的代码工作正常,但当我尝试获取
其他整数类型(例如char
或unsigned int
)时失败。读取这些类型的代码与读取 int
的代码完全相同。我可以复制我想阅读的所有其他整数类型的代码,但我宁愿为所有整数类型定义一个函数模板。
我已经尝试过以下操作:
struct Scanner
{
template <typename T>
typename enable_if<boost::is_integral<T>, T>::type get();
};
这就像一个魅力,但我不确定如何让 Scanner::get
再次运行。那么,我该如何编写代码,以便可以执行 scanner.get
和 scanner.get
并具有单个定义读取所有整数类型?
更新:额外问题:如果我想根据某些特征接受多个类别怎么办?例如:如果我想要三个分别接受 (i) 整型 (ii) 浮点类型 (iii) 字符串的 get
函数,我应该如何解决这个问题。
Consider the following example:
struct Scanner
{
template <typename T>
T get();
};
template <>
string Scanner::get()
{
return string("string");
}
template <>
int Scanner::get()
{
return 10;
}
int main()
{
Scanner scanner;
string s = scanner.get<string>();
int i = scanner.get<int>();
}
The Scanner
class is used to extract tokens from some source. The above code works fine, but fails when I try to get
other integral types like a char
or an unsigned int
. The code to read these types is exactly the same as the code to read an int
. I could just duplicate the code for all other integral types I'd like to read, but I'd rather define one function template for all integral types.
I've tried the following:
struct Scanner
{
template <typename T>
typename enable_if<boost::is_integral<T>, T>::type get();
};
Which works like a charm, but I am unsure how to get Scanner::get<string>()
to function again. So, how can I write code so that I can do scanner.get<string>()
and scanner.get<any integral type>()
and have a single definition to read all integral types?
Update: bonus question: What if I want to accept more than one range of classes based on some traits? For example: how should I approach this problem if I want to have three get
functions that accept (i) integral types (ii) floating point types (iii) strings, respectively.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新“如果我想根据某些特征接受多个类别怎么办?”
Update "What if I want to accept more than one range of classes based on some traits?"
遵循另一个模板。这是您想要的一般模式:
Defer to another template. Here's the general pattern for what you want: