作为函子模板的模板实参
template argument as functor template
本文关键字:实参 更新时间:2023-10-16
我试图创建一个线程类,从适配器执行一个函子。代码显示了我的尝试。
#include <iostream>
struct null_t { };
typedef void (*thread_func_t)();
typedef void (*thread_func_2_t)(int);
template <typename F, typename P = null_t>
class adapter
{
public:
adapter(F f, P p = null_t()) : _f(f), _p(p) {}
void operator ()()
{
_f(_p);
}
private:
F _f;
P _p;
};
template <typename T>
class thread
{
public:
explicit thread(T f) : _f(f) { }
void run()
{
_f();
}
private:
T _f;
};
void show_hello()
{
std::cout << "hello" << std::endl;
}
void show_num(int x)
{
std::cout << "show_num: " << x << std::endl;
}
int main()
{
thread<adapter<thread_func_t> > t_a(adapter<thread_func_t>(&show_hello));
t_a.run();
int i = 666;
thread<adapter<thread_func_2_t, int> > t_b(adapter<thread_func_2_t, int>(&show_num, i));
t_b.run();
}
编译错误:
$ /usr/bin/g++-4.4 func.cpp -o func
func.cpp: In function ‘int main()’:
func.cpp:51: error: request for member ‘run’ in ‘t_a’, which is of non-class type ‘thread<adapter<void (*)(), null_t> >(adapter<void (*)(), null_t>&)’
1) adapter
不准备调用没有参数的函数(我不知道怎么做)。
2)我已经尝试thread
接收模板参数没有成功。
我正试图做几乎与下面的示例相同的事情(此适配器不适用于没有参数的函数):
typedef void (*WorkerFunPtr)(const std::string&);
template<typename FunT, typename ParamT>
struct Adapter {
Adapter(FunT f, ParamT& p) : f_(f), p_(&p) {}
void operator( )( ) {
f_(*p_);
}
private:
FunT f_;
ParamT* p_;
};
void worker(const std::string& s) { std::cout << s << 'n'; }
int main( ) {
std::string s1 = "This is the first thread!";
boost::thread thr1(Adapter<WorkerFunPtr, std::string>(worker, s1));
thr2.join( );
}
这是最令人烦恼的解析问题。您需要在构造函数参数周围再添加一对括号,否则该行将被视为函数声明。
thread<adapter<thread_func_t> > t_a((adapter<thread_func_t>(&show_hello)));
另外,考虑使用boost::thread
,因为它将把您的代码变成一个三行代码。
为了完整起见,另一种解决这个令人烦恼的问题的方法是先创建一个适配器实例,然后在构造时将其传递给线程类:
adapter<thread_func_t> some_adapter_delegate_thingy(&show_hello);
thread<adapter< thread_func_t> > t_a(some_adapter_delegate_thingy);
使用统一的初始化语法"{}"
thread<adapter<thread_func_t> > t_a{adapter<thread_func_t>(&show_hello)};
避免了这个问题
相关文章:
- 非类型引用形参/实参
- 成员函数指针的模板实参演绎
- 函数和函数作为模板函数的实参
- Const到非Const指针模板实参的转换
- 传递boost::函数,该函数接受一个模板实参作为默认为NULL的形参
- 当实参是初始化列表而形参是引用时,重载解析
- 函数模板中返回类型的模板实参演绎
- ostream_iterator的模板实参-每个元素都是pair
- c++——关于使用默认实参的困惑
- std::shared_ptr、继承和模板实参演绎的问题
- 将操作符转换为模板实参的特化
- 使用模板模板形参时,模板实参推导失败
- 带有const实参的c++构造函数
- 函数指针作为模板实参而不是函子
- c++临时对象绑定到实参并返回const引用值
- 调用对象作为默认实参的this
- 当涉及一个重载函数作为实参时,模板实参推导是如何工作的
- c++对const引用的实参依赖没有改变
- 为什么模板非类型形参指针和引用实参需要是全局的
- 将函数形参的实参解包到c++模板类