作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
下面的简单代码可以正常编译
class A {
int x[3];
public:
A() { x[0]=1; x[1]=2; x[2]=3; }
friend int const&at(A const&a, unsigned i) noexcept
{
return a.x[i];
}
friend int foo(A const&a, unsigned i) noexcept
{
int tmp = at(a,i);
return tmp*tmp;
}
};
但是如果把 friend 做成模板
class A {
int x[3];
public:
A() { x[0]=1; x[1]=2; x[2]=3; }
template<unsigned I>
friend int const&at(A const&a) noexcept
{
static_assert(I<3,"array boundary exceeded");
return a.x[I];
}
template<unsigned I>
friend int foo(A const&a) noexcept
{
int tmp = at<I>(a); // <- error: use of undeclared identifier 'at'
return tmp*tmp;
}
};
查找规则改变并且 clang 提示说错误,但是 gcc 和 icpc 没有。谁是对的(C++11)?以及如何为 clang 修复代码?
最佳答案
解决方法是将声明和定义分开:
class A {
int x[3];
public:
A() { x[0]=1; x[1]=2; x[2]=3; }
template<unsigned I>
friend int const&at(A const&a) noexcept;
template<unsigned I>
friend int foo(A const&a) noexcept;
};
template<unsigned I>
int const&at(A const&a) noexcept
{
static_assert(I<3,"array boundary exceeded");
return a.x[I];
}
template<unsigned I>
int foo(A const&a) noexcept
{
int tmp = at<I>(a);
return tmp*tmp;
}
关于c++ - 模板化友元函数查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15745776/
我是一名优秀的程序员,十分优秀!