gpt4 book ai didi

c++ - 函数对象方法对函数指针安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:42 25 4
gpt4 key购买 nike

我正在编写一个大量使用柯里化(Currying)对象和模板的项目。新decltype c++11 的特性意味着我可以开始接受没有明确定义返回类型的函数对象作为我的函数对象的 curry。相反,可以使用元函数提取返回类型,例如:

template<typename func_T, typename arg1_T>
struct unary_result {
typedef typename std::remove_reference<typename std::remove_cv<decltype(func_T()(arg1_T()))>::type>::type type;
};

给定一个函数对象:

struct foo {
int operator()(double) const;
};

(它不继承自 std::unary_function<double, int> 或定义它的 result_type ),我可以将它作为 unary_result<foo, double>::type 获取,这在我当前的代码中运行良好(一方面,它允许相同的函数对象针对不同的参数具有不同的行为)。

我的问题是:这将如何与函数指针交互?

我知道 STL 可以互换使用函数对象和函数指针,但从未真正使用过函数指针,所以我的直觉在这方面不是很好。我也知道这可能已经埋在 Boost 的某个地方了(我相信如果是这种情况,很快就会有人指出)。

最佳答案

您的 unary_result 应该可以很好地处理函数指针,尽管您在 std::remove_cv 之前需要一个额外的 typename

例子:

#include <type_traits>

template<typename func_T, typename arg1_T>
struct unary_result {
typedef typename std::remove_reference<typename std::remove_cv<decltype(func_T()(arg1_T()))>::type>::type type;
};

struct foo {
int operator()(double d) const
{
return d;
}

};

int bar(int i){
return i;
}

template<typename Func,typename Arg>
typename unary_result<Func,Arg>::type do_stuff(Func f,Arg a){
return f(a);
}

int main(){
int i=do_stuff(bar,42);
int d=do_stuff(foo(),3.1);
}

关于c++ - 函数对象方法对函数指针安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10594035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com