我正在使用Visual Studio 2013 RTM.
我正在尝试编写一个匹配多个字符之一的可变参数模板.递归案例很容易,但我正在努力编写基本案例.
template <char C, char... Cs>
auto char_match(char c) -> bool
{
return c == C || char_match<Cs...>(c);
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下作为基本案例,但它没有用.我知道你可以用类模板做到这一点,我很确定你不能用功能模板做到这一点.
template <>
auto char_match(char c) -> bool
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
错误C2912:'bool char_match(char)'的显式特化不是函数模板的特化
我也尝试在返回类型上使用std :: enable_if,但微软并不喜欢它.
template <char C, char... Cs>
typename std::enable_if<sizeof...(Cs) != 0, bool>::type char_match(char c)
{
return c == C || char_match<Cs...>(c);
}
template <char C, char... Cs>
typename std::enable_if<sizeof...(Cs) == 0, bool>::type char_match(char c)
{
return c == C;
}
Run Code Online (Sandbox Code Playgroud)
错误C2039:'type':不是'std :: enable_if'的成员
我很感激有关如何使这项工作的任何建议.
没有比主模板更专业的"专业化",所以这不起作用.我认为最简单的解决方案是使用类模板:
template <char ...> struct char_match_impl;
template <> struct char_match_impl<>
{
static bool go(char) { return false; }
};
template <char C, char ...Cs> struct char_match_impl<C, Cs...>
{
static bool go(char c) { return c == C || char_match_impl<Cs...>::go(c); }
};
template <char ...Cs>
bool char_match(char c)
{ return char_match_impl<Cs...>::go(c); }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |