在数字表达式中最方便地使用数字包装器 class 的选项是什么?
What options for most convenient usage of a numeric wrapper class in numeric expressions?
假设我有一个包装器 class 用于包含一些 "extra functions":
的数值
struct DblWrapper{
double value;
void func1(); // maybe to print nicely
void func2(); // maybe to register this for automatic capture at data source
}
现在,我还想在数值表达式中尽可能方便地使用这个包装器的实例,例如:
DblWrapper a;
DblWrapper b;
DblWrapper d;
double c = a * b; // Best idea: overload operator () ( c = a() * b() )
d = c; // Best idea: overload operator =
或者实际上是否有一种方法可以全自动转换为 c = a * b
示例中给出的数值?
编写转换运算符和转换构造函数。
operator double() const
{
return value;
}
DblWrapper(double d) : value(d)
{
}
假设我有一个包装器 class 用于包含一些 "extra functions":
的数值struct DblWrapper{
double value;
void func1(); // maybe to print nicely
void func2(); // maybe to register this for automatic capture at data source
}
现在,我还想在数值表达式中尽可能方便地使用这个包装器的实例,例如:
DblWrapper a;
DblWrapper b;
DblWrapper d;
double c = a * b; // Best idea: overload operator () ( c = a() * b() )
d = c; // Best idea: overload operator =
或者实际上是否有一种方法可以全自动转换为 c = a * b
示例中给出的数值?
编写转换运算符和转换构造函数。
operator double() const
{
return value;
}
DblWrapper(double d) : value(d)
{
}