【发布时间】:2017-09-24 23:14:36
【问题描述】:
MCVE 胜于雄辩:
// int bar();
template <bool B> class Foo {
friend int ::bar() { return 123; }
};
int main()
{
Foo<false> f1;
Foo<true> f2;
}
使用 GCC 6 和 --std=c++14,这给了我:
a.cpp: In instantiation of ‘class Foo<true>’:
a.cpp:9:12: required from here
a.cpp:3:13: error: redefinition of ‘int bar()’
friend int ::bar() { return 123; }
^~
a.cpp:3:13: note: ‘int bar()’ previously defined here
现在,我不确定标准是怎么说的;但我知道编译器知道朋友没有在B 上进行模板化,它的定义也没有使用B。那么为什么不能应用“哦,同一个函数定义的所有内联副本都是一样的”规则呢?
【问题讨论】:
-
不确定标准是怎么说的,但这里的定义似乎不是
inline。尝试添加inline,看看是否有效? -
为什么不在类模板之外定义呢?
-
@Barry:这对我来说很方便,因为我在班级附近有一些相关的定义。
-
@anatolyg:隐含的
inline,因为它在类定义(IIANM)中;添加inline没有帮助。 -
“那么为什么不能应用“哦,同一个函数定义的所有内联副本都是一样的”? ——即使可以,为什么会呢?在任何其他情况下,该标准是否允许在同一翻译单元中重复定义同一函数?这种情况有什么特别之处,应该区别对待,例如
inline void f() {} inline void f() {}?
标签: c++ templates language-lawyer inline friend