普通函数不会覆盖模板函数

发布于 2024-09-19 22:43:38 字数 499 浏览 7 评论 0原文

我必须使用外部库,但如果使用 std::string 调用它,则会从以下模板函数及其显式专业化中收到“多重定义错误”。

template <typename T>
void foo(T& value);

template <>
void foo(std::string& value);

即使我将第二个函数更改为

void foo(std::string& value);

问题也是一样的。

根据[1],至少没有模板的版本(“普通旧函数”)应该优于模板版本。

有人知道问题可能出在哪里吗?

[1] http://www.gotw.ca/publications/mill17.htm

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?

[1] http://www.gotw.ca/publications/mill17.htm

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画▽骨i 2024-09-26 22:43:39

你打破了单一定义规则。

除非函数是内联的,否则它只能定义一次。如果您将函数标记为内联,只要定义匹配,就可以根据需要多次定义它们。模板函数的行为就像它们是隐式内联一样,因此您不会遇到模板错误。

但是,显式专业化或非模板函数并不是隐式内联的,并且因为您将其包含在多个翻译单元中,所以您会获得多个定义;这违反了规则。您应该将其标记为内联:(

template <>
inline void foo(std::string& value);

如果您在链接时间之前获得此信息,则需要包含防护措施。)

You're breaking the one-definition rule.

Unless a function is inline, it can only be defined once. If you mark the function as inline, so long as the definitions match they can be defined as often as desired. Template functions behave as if they were implicitly inline, 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 as inline:

template <>
inline void foo(std::string& value);

(If you're getting this before link time, you need include guards.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文