c++ - 具有不同模板参数作为输入的模板类的友元函数
问题描述
我有浮点格式的类,其中尾数和指数的大小可以指定为模板参数:
template <int _m_size, int _exp_size>
class fpxx {
public:
const int exp_size = _exp_size;
const int m_size = _m_size;
bool sign;
unsigned exp;
unsigned m;
...
}
我还有一个朋友 operator+ 来添加 2 个这样的数字:
friend fpxx<_m_size, _exp_size> operator+(const fpxx<_m_size, _exp_size> left, const fpxx<_m_size, _exp_size> right)
{
...
}
这工作正常。
它允许我做这样的事情:
fpxx<18,5> a, b, r;
r = a + b;
但是,我还可以创建一个 operator+ 朋友,它可以添加具有不同尾数和指数大小的数字。像这样:
fpxx<10,4> a;
fpxx<12,4> a;
fpxx<18,5> r;
r = a + b;
但我不知道如何为此声明函数。
这可能吗?
谢谢!汤姆
解决方案
制作您的运营商模板并制作它friend
,例如:
template <int _m_size, int _exp_size>
class fpxx {
public:
const int exp_size = _exp_size;
const int m_size = _m_size;
bool sign;
unsigned exp;
unsigned m;
template <int s1, int e1, int s2, int e2>
friend fpxx</*..*/> operator+(const fpxx<s1, e1>& left, const fpxx<s2, e2>& right);
};
template <int s1, int e1, int s2, int e2>
fpxx</*..*/> operator+(const fpxx<s1, e1>& left, const fpxx<s2, e2>& right)
{
//...
}
请注意,返回类型应在编译时固定。
推荐阅读
- css - 在 Bootstrap 4.5 中设置下拉项目的活动外观
- python - 聚类大量字符串
- mysql - Mysql select with 2 left join 显示第二个左连接的所有记录
- c++ - 如何在 Windows 上解析 std::put_time("%x") 创建的字符串?
- go - 将时间戳存储在变量中
- c++11 - type_traits 如何在编译时知道所有关于多态性的信息
- javascript - $.getJSON 是否重新排序数据?
- clickhouse - clickhouse MaterializedView 在对其运行查询后出现错误
- c# - 使用我的 int indexCounter 在 dataGridView 中选择整行
- c# - 我如何在 file.ini 中为同一部分创建多个 keyName?