【发布时间】:2015-11-16 03:33:04
【问题描述】:
我想延长?或重载?(不太确定叫什么) double 和其他基本类型使用的 sqrt() 函数,因此我自己的类可以使用它。这里称为“myType”。我将编写函数 sqrt() 以用于其参数是 myType 的情况。我希望 sqrt() 在用于基本类型时保持不变。这样我就可以编写一个涵盖这两种情况的模板。
例如。下面的关键是能够将 bar() 用于基本类型和 myType。不是 foo() 用于 myType 和 bar() 用于基本类型。这可以干净地完成吗?提前感谢您的帮助。
#include <math.h>
using namespace std;
class myType
{
public:
myType() {
}
double sqrt()
{
return 4;//just to return something
}
};
template<typename T> bool bar(T in)
{
if (sqrt(in) == 4) {// handels int and all sorts of other types but not my type
return true;
}
return false;
}
template<typename T> bool foo(T in)
{
if (in.sqrt() == 4) { //handles myType
return true;
}
return false;
}
int main() {
double y = 3;
bar(y);//This is great
myType x;
//bar(x);//this is the line I want to write
foo(x);//stuck doing this
}
【问题讨论】:
标签: c++ math overloading