【<专题讨论>[模板模式]<2>】成员模板和返回值重载
(1)成员模板
提供了一种类的成员函数的无限可能性
(2)返回值重载
使得我们的表达式调用语义依赖与使用上下文。
下面是我写的一个例子:
#include <windows.h>
#include <exception>
struct Return_overload
{
FARPROC data;
Return_overload(FARPROC data_)
: data(data_)
{}
template <typename T>
operator T () const
{
return (T)data;
}
};
struct Library
{
HMODULE handle;
Library(char const* name)
: handle(LoadLibrary(name))
{
if (handle == NULL)
throw std::bad_exception();
}
~Library()
{
FreeLibrary(handle);
}
Return_overload get_func(char const* name)
{
return GetProcAddress(handle, name);
}
};
int main()
{
Library lib("c:\\test.dll");
if (int (*show)(const char*)
= lib.get_func("_db2_show_sql_form")
)
show("c:\\db2sql\\define.ini");
// new :
// old :
// int (*show)(const char*) =
// (int (*)(const char*))GetProcAddress(...);
^^^^^^^^^^^^^^^^^^^^^
// int (*show)(const char*) =
// lib.get_func("_db2_show_sql_form");
// ^^^^^^^^^^^^^^^^^^^^^
// 此处没有了上面的返回值类型转换。
return 0;
}
注意^^^^^^^^^^部分,由于我们的成员模板和返回值重载
的使用,使得我们可以少写一个类型转换。
希望大家:
(1)探讨一下这个机制的一般化
(2)提供一些其他的应用代码例子
(3)弊端
我们在这里共同探讨一下,共同进步。