如何让我的模板类推断函数指针模板参数的返回和参数类型
我使用一个小帮助程序模板来包装不同的 Windows 函数来释放资源,例如:
template <typename Resource, typename ReturnType, ReturnType (WINAPI *GlobalFn)( Resource )>
struct GlobalWINAPIFn {
inline void release( Resource r ) { (void)GlobalFn( r ); }
};
此模板的实例化实际上作为参数传递给另一个模板(该模板期望给定类型公开 release
函数采用Resource
类型)。该帮助器用于轻松包装全局方法。
我像它一样使用它
// wraps BOOL WINAPI CloseHandle( HANDLE );
typedef GlobalWINAPIFn<HANDLE, BOOL, ::CloseHandle> HANDLEDestructor;
// wraps LONG WINAPI RegCloseKey( HKEY );
typedef GlobalWINAPIFn<HKEY, LONG, ::RegCloseKey> HKEYDestructor;
,但我想知道 - 有什么方法可以重写模板,以便我可以编写
typedef GlobalWINAPIFn<::CloseHandle> HANDLEDestructor;
typedef GlobalWINAPIFn<::RegCloseKey> HKEYDestructor;
并且返回类型会自动推导?某种类型工厂功能?
I'm using a little helper template to wrap different Windows functions for releasing resources, such as:
template <typename Resource, typename ReturnType, ReturnType (WINAPI *GlobalFn)( Resource )>
struct GlobalWINAPIFn {
inline void release( Resource r ) { (void)GlobalFn( r ); }
};
Instantiations of this template are actually passed as an argument to another template (which expects the given type to expose a release
function which takes the type Resource
). This helper is used to easily wrap global methods.
I'm using it like
// wraps BOOL WINAPI CloseHandle( HANDLE );
typedef GlobalWINAPIFn<HANDLE, BOOL, ::CloseHandle> HANDLEDestructor;
// wraps LONG WINAPI RegCloseKey( HKEY );
typedef GlobalWINAPIFn<HKEY, LONG, ::RegCloseKey> HKEYDestructor;
It works, but I wonder - is there any way to rewrite the template so that I can just write
typedef GlobalWINAPIFn<::CloseHandle> HANDLEDestructor;
typedef GlobalWINAPIFn<::RegCloseKey> HKEYDestructor;
And the return types are deduces automatically? Some sort of type factory function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以看一下
boost::function_traits
http://www.boost.org/doc/libs/1_34_0/libs/function/function_traits.htmlYou might take a look at
boost::function_traits
http://www.boost.org/doc/libs/1_34_0/libs/functional/function_traits.html