c – 通过模板传递函数时的推断返回类型
发布时间:2020-12-16 07:03:39 所属栏目:百科 来源:网络整理
导读:我的问题是让编译器根据模板传递的函数的返回类型推断函数的返回类型. 有什么方法可以称之为 foobar(7.3) 代替 foodouble,int,bar(7.3) 在这个例子中: #include cstdiotemplate class T,class V,V (*func)(T)V foo(T t) { return func(t); }int bar(double
我的问题是让编译器根据模板传递的函数的返回类型推断函数的返回类型.
有什么方法可以称之为 foo<bar>(7.3) 代替 foo<double,int,bar>(7.3) 在这个例子中: #include <cstdio> template <class T,class V,V (*func)(T)> V foo(T t) { return func(t); } int bar(double j) { return (int)(j + 1); } int main() { printf("%dn",foo<double,bar>(7.3)); } 解决方法
如果你想把bar作为模板参数,我担心你只能接近这个:
#include <cstdio> template<typename T> struct traits { }; template<typename R,typename A> struct traits<R(A)> { typedef R ret_type; typedef A arg_type; }; template <typename F,F* func> typename traits<F>::ret_type foo(typename traits<F>::arg_type t) { return func(t); } int bar(double j) { return (int)(j + 1); } int main() { printf("%dn",foo<decltype(bar),bar>(7.3)); } 如果要避免重复条形图名称,也可以定义宏: #define FXN_ARG(f) decltype(f),f int main() { printf("%dn",foo<FXN_ARG(bar)>(7.3)); } 或者,您可以让bar成为函数参数,这可以让您的生活更轻松: #include <cstdio> template<typename T> struct traits { }; template<typename R,typename A> struct traits<R(A)> { typedef R ret_type; typedef A arg_type; }; template<typename R,typename A> struct traits<R(*)(A)> { typedef R ret_type; typedef A arg_type; }; template <typename F> typename traits<F>::ret_type foo(F f,typename traits<F>::arg_type t) { return f(t); } int bar(double j) { return (int)(j + 1); } int main() { printf("%dn",foo(bar,7.3)); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 用 Swift 架构 iOS 应用的正确姿势!
- ajax – #! (hashbang)和Google SEO
- 如果字符串字段以加号()开头,则更新Sqlite表?
- 关于Flex 4 里 TextInput 和TextArea 不能输入中文的问题
- objective-c-CI Filter创建黑白图像?
- 读写Stellaris Cortex-M3片上RAM和FLASH
- postgresql post-install error
- ruby-on-rails – Rails 3.2 OSX:无法安装rmagick gem
- ruby – 执行gem时,未知命令
- React Native 向iOS项目中添加React Native支持