gpt4 book ai didi

c++ - 好友模板功能说明

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

我有一个类,其中与模板化运算符 >> 建立了友元:

class MyInputStream
{
...
private:
std::istream& impl;

template<class T>
friend MyInputStream& operator>> (MyInputStream& stream, T& outParam);
}

现在我定义运算符>>

   template<class T>
MyInputStream& operator>> (MyInputStream& stream, T& outParam)
{
stream.impl >> outParam;
return stream;
}

一切正常。

但是当我添加模板的特化时出现问题,例如“int”模板参数

   template<>
MyInputStream& operator>> (MyInputStream& stream, int& outParam)
{
stream.impl >> outParam;
return stream;
}

然后我收到链接错误,指出 .obj 文件中已经定义了 int 的模板运算符。请告诉我应该做什么。

最佳答案

函数模板的显式特化就像任何其他函数一样,它只能定义一次。

要么在 header 中声明特化并将其定义在 .cpp 文件中,要么在 header 中将其定义为 inline

您还需要确保在函数模板的任何使用导致 int 函数模板的隐式实例化之前声明了特化。如果尚未在需要的地方声明特化,则主模板将用于生成隐式实例化。

(注意,这与作为友元的函数没有任何关系,相同的规则适用于所有函数模板特化)

关于c++ - 好友模板功能说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789761/

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