c++ - 带有模板函数的 boost::bind()

标签 c++ boost boost-bind

如何boost::bind() 模板函数?

我希望此代码(受 boost::bind bind_as_compose.cpp 示例启发)编译并运行。请注意,评估与 bind_as_compose.cpp 示例中的不同; fff() 开始运行之前 kkk():

template<class F> 
void fff(F fun)
{
   std::cout <<  "fff(";
   fun();
   std::cout << ")";
}

void kkk()
{
   std::cout <<  "kkk()";
}

void test()
{
   fff(kkk);             // "Regular" call - OK
   // bind(fff,kkk)();   // Call via bind: Does not compile!!!
}

打印:

fff(kkk())
fff(kkk())

更新: 基于this answer ,我让这个工作:

void (&fff_ptr)(void(void)) = fff;
boost::bind(fff_ptr, kkk)();

但是,这需要我明确指定实例化类型,哪种类型的目的...

更新 2 最终,我想将绑定(bind)对象作为 nullary 可调用类型参数传递给另一个函数,例如 fff()。在这种情况下,显式类型是什么?

假设我有另一个模板函数ggg():

template<class F> 
void ggg(F fun)
{
   std::cout <<  "ggg(";
   fun();
   std::cout << ")";
}

我如何使用绑定(bind)来获得此输出:fff(ggg(kkk()))
这似乎不起作用:

boost::bind(fff<void()>, boost::bind(ggg<void()>, kkk))();

最佳答案

#include <iostream>
#include <functional>

template<class F>
void fff(F fun)
{
std::cout << "fff(";
fun();
std::cout << ")" <<  std::endl;
}

void kkk()
{
std::cout << "kkk()";
}

int main()
{
    // "Regular" call - OK
    fff(kkk);
    // you have to specify template parameters:
    std::bind(&fff<void()>, &kkk)();
    return 0;
}

输出是:

zaufi@gentop /work/tests $ g++11 -o bind_test bind_test.cc
zaufi@gentop /work/tests $ ./bind_test
fff(kkk())
fff(kkk())

根据问题的第二部分:

boost::bind(fff, boost::bind(ggg, kkk))();

这不会编译,因为外部 bind 的参数不是 void() 类型! 它实际上是一个非常复杂的模板,绝对不能转换void()

关于c++ - 带有模板函数的 boost::bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18035662/

相关文章:

c++ - 可以使用 boost::reference_wrapper 将引用存储在 STL 容器中吗?

c++ - 使用 websocketpp 时出现 "No matching function for call to bind"

c++ - VS2008 C++项目编译的外化参数

C++ - 基本井字棋程序打印空白屏幕

c++ - 使用 C++/Boost 绕过阻塞输入流

C++ 帮助 boost::ptr_map/boost::checked_delete 失败

c# - 从 C++ 传递到 C# 的字符串打印空白

boost::shared_ptr vector 的 C++ 静态初始化

c++ - 将值传递给 atexit

c++ - 用类成员函数调用AfxBeginThread?