C 风格字符串的模板特化
我很难获得接受常规 c 样式字符串的模板专业化的正确语法。例如
namespace RubyUtils
{
template<class T> VALUE toValue(const T& v);
};
template<> VALUE toValue(char const* & v)
{
return toValue<string>(v);
}
,然后在调用站点
return RubyUtils::toValue("Life the universe and everything");
给出一个错误,
unresolved external symbol "unsigned long __cdecl RubyUtils::toValue<char const [33]>(char const (&)[33])"
我应该如何构建专业化以启用 c 样式字符串的传递?
更新:修复了模板专业化,使其具有正确的语法 template =>模板>>
I'm having difficulty getting the correct syntax for a template specialisation which accepts a regular c-style string. For example
namespace RubyUtils
{
template<class T> VALUE toValue(const T& v);
};
template<> VALUE toValue(char const* & v)
{
return toValue<string>(v);
}
and then at the call site
return RubyUtils::toValue("Life the universe and everything");
gives an error
unresolved external symbol "unsigned long __cdecl RubyUtils::toValue<char const [33]>(char const (&)[33])"
how should I structure the specialisation to enable passing in c-style strings?
UPDATE: Fixed the template specialisation to have correct syntax template => template<>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您遇到的问题可能与您定义了两个模板有关 - 一个在命名空间内部,一个在命名空间之外。该错误可能是由于这种混乱造成的。
但更重要的是,作为一般规则,您不想想要专门化函数模板。函数的模板专门化有许多与之相关的时髦规则,这些规则几乎普遍会导致错误的调用。相反,只需使用常规函数重载:
函数重载的工作方式是,使用 C 样式字符串调用
toValue
函数将导致非模板toValue
在之前被选中。toValue
模板,本质上是为您进行专门化。更一般地说,对于函数模板,更喜欢使用重载而不是专门化。它只是更安全。I think that the problem you're encountering is probably related to the fact that you've defined two templates - one inside of the namespace, and one out. The error is likely due to this confusion.
But more importantly, as a general rule, you do not want to specialize function templates. Template specialization for function has lots of funky rules associated with it that almost universally result in the wrong thing getting called. Rather, just use regular function overloading:
The way function overloading works, calling the
toValue
function with a C-style string will cause the non-templatetoValue
to get selected ahead of thetoValue
template, essentially doing the specialization for you. More generally, with function templates, prefer using overloading to specialization. It's just safer.