gpt4 book ai didi

c++ - 模板化友元函数查找

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:02 24 4
gpt4 key购买 nike

下面的简单代码可以正常编译

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com