C++虽然是不能仅仅通过返回值重载函数的,可是,我们往往会想:要是支持返回值重载就好了。此刻,我就从C++的某个颇受争议的角落,为您掘客一点对象。
假设有这样一个函数:
type getvalue(const DBField& fd);
但是,DBField实际的数据范例对付getvalue来说,并不相识,一个常见的办理方案是:
template<typename T>
T getvalue(const DBField& fd);
但是,这样虽然是一个步伐,并且是不错的步伐。问题在于,有些时候我们并不利便提供这个T,好比,是一个运算符重载的时候。别的,当我们不想过早确定返回值范例的时候,我们也不肯意提供这个范例T。办理的步伐很简朴,提供一个间接层:
string getvalue(const DBField& fd);
int getvalue_int(const DBField& fd);
Result getvalue(const DBField& fd)
{
return Result(fd);
}
看看如何实现Result:
struct Result{
const DBField& fd;
explicit Result(const DBField& f) : fd(f){}
operator string() const { return getvalue_string(fd);}
operator int() const { return getvalue_int(fd);}
};
此刻,让我们输出数据:
void print_string(const string& str){...}
void print_int(int i){...}
如下利用:
print_string(getvalue(DBField));
print_int(getvalue(DBField));
虽然,把范例写进名字可不是什么大度的做法,既然你喜欢重载,没问题:
template <typename T>
T getvalue(const DBField& fd);
struct Result{
const DBField& fd;
explicit Result(const DBField& f) : fd(f){}
template<typename T>
operator T() const { return getvalue<T>(fd);}
};
这个要领问题在于,必需在某个竣事点提供详细的范例信息,这也是为什么我们要写两个print而不是直接用cout输出的原因。但是,话说返来,既然你规划仅仅通过返回值来重载,总要汇报代码,返回值是什么吧?
这里展示了懒惰计较的能力,通过一个间接层,把真正的计较时刻延迟到必须的时候。也许你对返回值重载不屑一顾,可是这个能力长短常有用的。下一次,我将用懒惰计较的要领,展示另一种能力。
#include <iostream>
#include <string>
using namespace std;
string getvalue_slow(const int&)
{
return "getvalue_slow";
}
string g_fast = "getvalue_fast";
const char* getvalue_fast(const int&)
{
return g_fast.c_str();
}
struct Result
{
const int& i;
explicit Result(const int& r) : i(r){}
operator string() const{ return getvalue_slow(i);}
operator const char* () const { return getvalue_fast(i);}
};
Result getvalue(const int& i)
{
return Result(i);
}
void print_const(const char* str)
{
cout << str << endl;
}
void print(const string& str)
{
cout << str << endl;
}
int main()
{
print(getvalue(1));
print_const(getvalue(1));
}