gpt4 book ai didi

c++ - 模板类中友元声明的附加模板参数?

转载 作者:行者123 更新时间:2023-11-28 04:09:18 24 4
gpt4 key购买 nike

为了一些全局函数

template<typename T, int count>
void func (const Obj<T>& obj) {
for (int i = 0; i < count; i++)
std::cout << obj.value << std::endl;
}

能够访问私有(private)字段value一些模板类

template<typename T>
class Obj {
public:
Obj (T value);
private:
T value;
};

template<typename T>
Obj<T>::Obj (T value) : value(value) {}

我们需要声明func<T, count> Obj<T>的 friend .但是func<T, count>在我们让它成为Obj<T>的 friend 之前必须声明,为此我们需要转发声明 Obj<T> .生成的代码如下所示

// Forward declarations
template<typename T>
class Obj;

template<typename T, int count>
void func (const Obj<T>& obj);

// Obj<T>
template<typename T>
class Obj {
public:
Obj (T value);

template<int count>
friend void func<T, count> (const Obj<T>& obj);
private:
T value;
};

template<typename T>
Obj<T>::Obj (T value) : value(value) {} // <-- ERROR

// func<T>
template<typename T, int count>
void func (const Obj<T>& obj) {
for (int i = 0; i < count; i++)
std::cout << obj.value << std::endl;
}

但这使得 gcc 提示“在主模板声明中无效使用模板 ID 'func'”,那么我实际上如何声明 func<T, count> Obj<T>的 friend 对于每个 count ?根据this answer我只需要用这个替换 friend 声明

template<typename T1, int count>
friend void func (const Obj<T1>& obj);

据我所知这将使 func<T1, count> Obj<T>的 friend 不管是否T1T比赛,这是荒谬的。是否可以申报func<T, count> Obj<T>的 friend 没有其他Obj<T1> ? (最好以将 func<T, count> 的定义保持在 Obj<T> 定义之外的方式)

(我知道我可以让 count 成为一个真实的参数,但上面的例子只是我真实代码的简化。实际上,我试图以某种方式为某个类 std::basic_ostream<CharT, Traits>& operator<< (std::basic_ostream<CharT, Traits>& stream, const Obj<T>& obj) 重载 Obj<T>允许 operator<< 访问 Obj<T> 的私有(private)字段。)

最佳答案

friend 声明必须匹配任何可能的前向声明,当然还有定义,包括模板参数。

这意味着你需要例如

template<typename U, int count>
friend void func(const Obj<U>& obj);

类模板参数 T 和函数模板参数 U 是否不同并不重要,因为无论如何都会对正确的函数进行调用。

例子:

Obj<int> int_obj;
Obj<float> float_obj;

func<X>(int_obj); // Will call void func<int, X>(int_obj)
func<X>(float_obj); // Will call void func<float, X>(float_obj)

作为替代方案,您可以在类定义中定义内联函数,这样您就不需要提供TU 模板参数:

template<int count>
friend void func(const Obj<T>& obj)
{
// Implementation...
}

在这两种情况下,您实际上都不应该有一个 func 的前向声明(如我的评论中所述)。

关于c++ - 模板类中友元声明的附加模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154678/

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