奇技淫巧C++之返回值重载

王朝c/c++·作者佚名  2008-06-01
窄屏简体版  字體: |||超大  

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));

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航