为template类定义numeric_limits-max函数
defining numeric_limits max function for template class
我在为模板类定义函数max时遇到问题。在这个类中,我们把一个数保持为不是简单的整数,而是一些数字系统中的数字向量。通过定义numeric_limits,我需要返回建立在定义的数字系统上的最大数的表示。
当我试图返回具有最大表示的类时,我会遇到很多错误,但当返回integer时它会起作用。
我的模板类:
template<int n,typename b_type=unsigned int,typename l_type=unsigned long long,long_type base=bases(DEC)>
class NSizeN
{
public:
int a_size = 0;
vector <b_type> place_number_vector; // number stored in the vector
NSizeN(int a){ //constructor
do {
place_number_vector.push_back(a % base);
a /= base;
a_size ++;
} while(a != 0);
}
void output(ostream& out, NSizeN& y)
{
for(int i=a_size - 1;i >= 0;i--)
{
cout << (l_type)place_number_vector[i] << ":";
}
}
friend ostream &operator<<(ostream& out, NSizeN& y)
{
y.output(out, y);
return out << endl;
}
}
在.h文件的末尾,我有这样的:
namespace std{
template<int n,typename b_type,typename l_type,long_type base>
class numeric_limits < NSizeN< n, b_type, l_type, base> >{
public :
static NSizeN< n, b_type, l_type, base> max(){
NSizeN< n, b_type, l_type, base> c(base -1);
return c;
}
}
我已经用const和constexpr尝试过了,但它不起作用。我不知道如何消除这些错误:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to'std::basic_ostream<char>&&'
std::cout << std::numeric_limits<NSizeN<3> >::max() << endl;
error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = NSizeN<3>]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
这就是我主要想做的:
std::cout << std::numeric_limits<NSizeN<3> >::max() << endl;
这是我的作业,所以不要评判做这件事的方式,因为这是我老师的选择,我希望我能比较全面地提出我的问题。
您面临的问题是,您试图将max()
函数返回的临时绑定到输出运算符的非常数引用。
最干净的解决方案是将输出运算符声明为:
friend ostream &operator<<(ostream& out, const NSizeN& y)
并且您的output
功能为
void output(ostream& out) const
注意,我还删除了output
函数未使用的第二个参数。const引用可以绑定到l值和r值,因此它也适用于max()
函数返回的临时值。
编辑正如@n.m.所指出的,您也不使用实际传递给operator <<
的流,而只使用std::cout
。实现它的正确方法是简单地使用流(在您的情况下,只需在output
函数中将cout << ...
替换为out << ...
。这将使std::cerr << std::numeric_limits<NSizeN<3> >::max();
等语句按预期工作。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- std::max() 函数与定点实现的比较中的问题
- 没有函数模板的实例"max"与参数列表参数类型匹配(int、int)
- 为什么在这种情况下不能将 Max 用作函数?
- 从递归向后选择排序函数调用 max 和交换函数
- 为什么 c++ 编译器在对两种不同类型的数值变量使用"std::max()"函数时会出现错误
- 自动变量可存储函数指针到std :: max
- 如何查找具有一组整数的函数的'max absolute sum'
- 在调试中,如何知道对函数的重复调用中参数的统计数据(max-min,average,distribution..)
- 当我尝试编译程序时,我遇到了一堆错误,例如:'std::max':找不到匹配的重载函数
- int max(一个变量)和 int max(int ,int)之间没有冲突,这是 C++ 中的一个函数
- c++ PPL 并行工作 - 归约类 'combinable' 中的函数 max()
- 在Armadillo稀疏矩阵中使用max函数时出错
- 如何将大于 std::numeric_limits<fundamental_type>::max() 的值传递给函数?
- 为template类定义numeric_limits-max函数
- 如何在c++中创建一个max函数来搜索数列中的最大值?
- 为数组创建c++ max函数:处理数组大小为0的情况的正确方法是什么?