[英]template argument as functor template
我正在嘗試創建一個從適配器執行函子的線程類。 代碼顯示了我的嘗試。
#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
,因為它會將您的代碼變成三行代碼。
使用統一的初始化語法“{}”
thread<adapter<thread_func_t> > t_a{adapter<thread_func_t>(&show_hello)};
避免了這個問題。
為了完整起見,解決這個棘手問題的另一種方法是首先創建一個適配器實例,然后在構造過程中將其傳遞到您的線程類中:
adapter<thread_func_t> some_adapter_delegate_thingy(&show_hello);
thread<adapter< thread_func_t> > t_a(some_adapter_delegate_thingy);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.