c++ - boost::bind()-类似的东西,但用于函数调用

标签 c++ c++11 boost function-binding

给定boost::bindstd:: 等价物,我可以这样做:

int f(int a, int b)
{
    return a + b;
}

auto f_two = boost::bind(f, 1, 1);

因此 f_two() 将通过有效地调用中间函数返回 2,该中间函数通过任何实现机制调用 f(1, 1),也许类似于:

double f_two_caller()
{
     return f(stored_arg_1, stored_arg_2);
}

但是,我的用例是我想绑定(bind)一个前缀函数,所以我可以说:

auto f_print = boost::bind(printf, "Hello, world!\n");
auto f_print_and_two = boost::bind_with_prefix(f, f_print, 1, 1);

所以 f_print_and_two() 有效地执行:

double f_print_and_two_caller()
{
    f_print(f_print.stored_arg_1);
    return f(stored_arg_1, stored_arg_2);
}

我确定该技术有一个合适的名称,我可以用它来查找解决方案,但我现在想不出...

最佳答案

template<class First, class Second>
struct compose_t {
    First first;
    Second second;
    template<class...Args>
    auto operator()(Args&&...args)
    -> decltype( std::declval<Second&>()( std::declval<First&>()( std::declval<Args>()... ) ) )
    { return second(first( std::forward<Args>(args)... ) ); }
};
template<class First, class Second>
compose_t<typename std::decay<First>::type, typename std::decay<Second>::type>
compose( First&& first, Second&& second ){ return {std::forward<First>(first), std::forward<Second>(second)}; }

这是函数式组合。

auto f_print = std::bind(printf, "Hello, world!\n");

auto f_print_and_two = std::bind( compose(f, f_print), 1, 1 );

int main() {
    f_print_and_two();
}

done .

请注意,函数组合可以链接。您甚至可以根据上述内容编写一个可变的 compose 函数。

关于c++ - boost::bind()-类似的东西,但用于函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52773022/

相关文章:

c++ - 这个时钟滴答适用于 Intel i3 吗?

c++ - 为什么 C++ 使用 memset(addr,0,sizeof(T)) 来构造一个对象?标准错误还是编译器错误?

c++ - 谁能告诉我我的代码有什么问题?

c++ - 如何抑制 boost::spirit 中的跳过来解析带引号的字符串?

c++ - Boost::asio TCP 服务器——从客户端读取消息

c++ - boost asio 在线程中运行 io_service

c++ - 在 C++ 中定义一个类

c++ - Keccak 输出错误

c++ - 有什么可以一般地反转 C++ Comparator 类型吗?

c++ - 如何在类声明中获取类的 decltype