普通函数不会覆盖模板函数
我必须使用外部库,但如果使用 std::string 调用它,则会从以下模板函数及其显式专业化中收到“多重定义错误”。
template <typename T>
void foo(T& value);
template <>
void foo(std::string& value);
即使我将第二个函数更改为
void foo(std::string& value);
问题也是一样的。
根据[1],至少没有模板的版本(“普通旧函数”)应该优于模板版本。
有人知道问题可能出在哪里吗?
I have to use an external library, but am getting a "multiple definition error" from following template function and its explicit specialization, if it gets called with a std::string.
template <typename T>
void foo(T& value);
template <>
void foo(std::string& value);
even if I change the 2nd function to
void foo(std::string& value);
the problem is the same.
According to [1] at least the version without a template (the "plain old function") should be prefered over the template version.
Does anybody have a clue, where the problem could be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你打破了单一定义规则。
除非函数是内联的,否则它只能定义一次。如果您将函数标记为内联,只要定义匹配,就可以根据需要多次定义它们。模板函数的行为就像它们是隐式
内联
一样,因此您不会遇到模板错误。但是,显式专业化或非模板函数并不是隐式内联的,并且因为您将其包含在多个翻译单元中,所以您会获得多个定义;这违反了规则。您应该将其标记为
内联
:(如果您在链接时间之前获得此信息,则需要包含防护措施。)
You're breaking the one-definition rule.
Unless a function is
inline
, it can only be defined once. If you mark the function asinline
, so long as the definitions match they can be defined as often as desired. Template functions behave as if they were implicitlyinline
, so you don't get errors with templates.However, an explicit specialization or non-template function is not implicitly
inline
and because you're including it in multiple translation units, you get multiple definitions; this breaks the rule. You should mark it asinline
:(If you're getting this before link time, you need include guards.)