我正在使用一组类,我的主要代码如下所示:
main.cpp
#include "calc.h"
int main() {
neg_inf nif;
pos_inf pif;
limit<double, infinity> l( 3.4, nif, pif, 2.2 )
std::cout << "value dx = " << l.value() << '\n'
<< "lower lim = " << l.lower() << '\n'
<< "upper lim = " << l.upper() << '\n'
<< "step_size = " << l.step() << '\n';
return EXIT_SUCCESS;
}
预期输出应为:
value dx = 3.4
lower lim = -inf
upper lim = inf
step_size = 2.2
以下是我的类:
calc.h
#pragma once
#include <cmath>
#include <iostream>
#include <limits>
#include <type_traits>
struct infinity {
protected:
infinity() = default;
};
struct pos_inf : public infinity {
constexpr double operator()() { return std::numeric_limits<double>::infinity(); }
};
struct neg_inf : public infinity {
constexpr double operator()() { return -std::numeric_limits<double>::infinity(); }
};
std::ostream& operator<<( std::ostream& os, const pos_inf& inf );
std::ostream& operator<<( std::ostream& os, const neg_inf& inf );
template<typename dX, class bound>
class limit {
dX dx;
bound lowerBound;
bound upperBound;
double step_size;
public:
limit( dX x, bound lower, bound upper, double step = 1 ) :
dx{ x }, lowerBound{ lower }, upperBound { upper }, step_size { step }
{}
dX value() const { return dx; }
bound lower() const { return lowerBound; }
bound upper() const { return upperBound; }
double step() const { return step_size; }
};
calc.cpp
#include "calc.h"
std::ostream& operator<<( std::ostream& os, const pos_inf& inf ) {
// originally intended to do:
// return os << inf(); // but fails to compile
auto v = pos_inf()(); // this works
return os << v;
}
std::ostream& operator<<( std::ostream& os, const neg_inf& inf ) {
// same as above...
auto v = neg_inf()();
return os << v;
}
然而,在main.cpp Visual Studio2017中生成了这个编译器错误:
c:\***\main.cpp(33): error C2679: binary '<<': no operator found which takes a right-hand operand of type 'bound' (or there is no acceptable conversion)
1> with
1> [
1> bound=infinity
1> ]
基于这行代码:
<< "lower lim = " << l.lower() << '\n'
并在l.lower()
中失败
但是,如果我在main中执行此操作:
#include "calc.h"
int main() {
neg_inf nif;
pos_inf pif;
std::cout << nif << '\n' << pif << '\n'
return EXIT_SUCCESS;
}
我正在获取输出:
-inf
inf
这告诉我,我的operator<<()
适用于继承的结构,但是当我将它的父类型作为模板参数传递并将派生类型传递到limit
类的构造函数中时,operator<<()
不能解析。这似乎是一个模棱两可的问题,但我不确定如何解决这个问题。我在这里遗漏或忽略了什么?
顺便说一句,有没有更优雅的方式来表示-/+inf
呢?我在这里使用继承,因为+
和-
inf
不是数字,而是一个概念,它们彼此相似,但指向不同的方向。因此,当我将无穷大类型作为模板参数传递时,我希望能够将下限设置为-inf,将上限设置为+inf。我希望绑定类型是一个模板,因为我可能想要使用整数界限或双精度界限,例如,在[-1,1]
或[0.0,1.0]
之间,这些都是数值界限。我不知道如何用更优雅的方式表达无穷大,任何提示或建议都将不胜感激。
https://stackoverflow.com/questions/56656139
复制相似问题