[英]Unable to use std::bind with variadic template parameters
我正在為std::thread
實現包裝器,這將允許我在線程完成執行后檢索任意返回值。 當我使用C++11
,我使用的是較舊的ARM
體系結構,該體系結構不完全支持atomic int,這意味着我無法使用std::future
, std::promise
, std::packaged_task
等stl線程功能的介紹(至少我確實得到了std::thread
)。 我正在用gcc 4.8.4
進行測試。
在實施過程中,我遇到了這個bug ,這使我無法使用lambda捕獲可變參數模板參數。 不幸的是,我目前無法將編譯器升級到4.9。
我正在嘗試使用std::bind
實現替代方法,但是遇到了很多問題。 我不確定這些是我自己的編譯器錯誤還是實現錯誤。 來源如下:
#include <iostream>
#include <memory>
#include <thread>
#include <unistd.h>
#include <pthread.h>
class ConcurrentTaskBase
{
public:
ConcurrentTaskBase(int priority, const std::function<void()>& runTask)
: m_thread(),
m_active(true)
{
auto wrap = [this](int priority, const std::function<void()>& runTask)
{
//Unrelated pthread stuff that I commented out
// sched_param param{priority};
//
// int err = pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);
// if (err)
// cout << "failed to set new priority: " << err << endl;
runTask();
};
m_thread = std::thread(wrap, priority, runTask);
}
virtual ~ConcurrentTaskBase(void)
{
waitForCompletion();
}
void waitForCompletion(void)
{
if (m_active)
{
m_thread.join();
m_active = false;
}
}
private:
std::thread m_thread;
bool m_active;
};
template<class R, class... ArgTypes>
class ConcurrentTask;
template<class R, class... ArgTypes>
class ConcurrentTask<R(ArgTypes...)> : public ConcurrentTaskBase
{
public:
ConcurrentTask(int priority, const std::function<R(ArgTypes...)>& task, ArgTypes&&... args)
: ConcurrentTaskBase(priority, bindTask(task, std::forward<ArgTypes>(args)...))
{}
std::shared_ptr<R> getReturn(void) noexcept
{
waitForCompletion();
return m_storage;
};
private:
static std::function<void(void)> bindTask(const std::function<R(ArgTypes...)>& task, ArgTypes&&... args)
{
auto action = [task](ArgTypes&&... args) -> void
{
//Eventually m_storage = std::make_shared<R>(task(std::forward<ArgTypes>(args)...)); after bugs are fixed
task(std::forward<ArgTypes>(args)...);
return;
};
std::function<void(void)> bound = std::bind(action, std::forward<ArgTypes>(args)...);
return bound;
};
std::shared_ptr<R> m_storage;
};
int testFunction(int val)
{
std::cout << "Was given " << val << std::endl;
return val + 10;
}
int main()
{
ConcurrentTask<int(int)> task(20, testFunction, 5);
// shared_ptr<int> received = task.getReturn();
// testFunction(*received);
return 0;
}
這是我的編譯器輸出:
16:31:00 **** Incremental Build of configuration Debug for project TestLinuxMint ****
make all
Building file: ../src/TestLinuxMint.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -O0 -g3 -Wall -pthread -c -fmessage-length=0 -MMD -MP -MF"src/TestLinuxMint.d" -MT"src/TestLinuxMint.o" -o "src/TestLinuxMint.o" "../src/TestLinuxMint.cpp"
../src/TestLinuxMint.cpp: In instantiation of ‘static std::function<void()> ConcurrentTask<R(ArgTypes ...)>::bindTask(const std::function<_Res(_ArgTypes ...)>&, ArgTypes&& ...) [with R = int; ArgTypes = {int}]’:
../src/TestLinuxMint.cpp:58:84: required from ‘ConcurrentTask<R(ArgTypes ...)>::ConcurrentTask(int, const std::function<_Res(_ArgTypes ...)>&, ArgTypes&& ...) [with R = int; ArgTypes = {int}]’
../src/TestLinuxMint.cpp:91:53: required from here
../src/TestLinuxMint.cpp:76:90: error: conversion from ‘std::_Bind_helper<false, ConcurrentTask<R(ArgTypes ...)>::bindTask(const std::function<_Res(_ArgTypes ...)>&, ArgTypes&& ...) [with R = int; ArgTypes = {int}]::__lambda1&, int>::type {aka std::_Bind<ConcurrentTask<R(ArgTypes ...)>::bindTask(const std::function<_Res(_ArgTypes ...)>&, ArgTypes&& ...) [with R = int; ArgTypes = {int}]::__lambda1(int)>}’ to non-scalar type ‘std::function<void()>’ requested
std::function<void(void)> bound = std::bind(action, std::forward<ArgTypes>(args)...);
^
make: *** [src/TestLinuxMint.o] Error 1
16:31:01 Build Finished (took 319ms)
問題似乎在line 76
,從std::bind(*) to std::function<void(void)>
轉換失敗。 該代碼肯定仍在開發中,但我需要克服這個問題才能繼續前進。 我在SO上看過其他多個帖子,但是它們似乎都可以在可變參數模板參數上使用std :: bind而不出現問題。
解
由於kzraq和本文 , 這是我想出的最終解決方案(與該問題有關)。
資源:
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
#include <thread>
#include <type_traits>
#include <typeinfo>
#include <tuple>
#include <memory>
//------------------------------------------------------------------------------------------------------------
template <std::size_t... Ints>
struct idx_sequence
{
using type = idx_sequence;
using value_type = std::size_t;
static constexpr std::size_t size() noexcept { return sizeof...(Ints); }
};
//------------------------------------------------------------------------------------------------------------
template <class Sequence1, class Sequence2>
struct _merge_and_renumber;
template <std::size_t... I1, std::size_t... I2>
struct _merge_and_renumber<idx_sequence<I1...>, idx_sequence<I2...> >
: idx_sequence<I1..., (sizeof...(I1)+I2)...>
{
};
//------------------------------------------------------------------------------------------------------------
template <std::size_t N>
struct make_idx_sequence : _merge_and_renumber<make_idx_sequence<N/2>, make_idx_sequence<N - N/2> >
{
};
template<> struct make_idx_sequence<0> : idx_sequence<> { };
template<> struct make_idx_sequence<1> : idx_sequence<0> { };
//------------------------------------------------------------------------------------------------------------
template<typename Func, typename Tuple, std::size_t... Ints>
auto applyImpl(Func&& f, Tuple&& params, idx_sequence<Ints...>)
-> decltype(f(std::get<Ints>(std::forward<Tuple>(params))...))
{
return f(std::get<Ints>(std::forward<Tuple>(params))...);
};
template<typename Func, typename Tuple>
auto apply(Func&& f, Tuple&& params)
-> decltype(applyImpl(std::forward<Func>(f),
std::forward<Tuple>(params),
make_idx_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>{}))
{
return applyImpl(std::forward<Func>(f),
std::forward<Tuple>(params),
make_idx_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>{});
};
class ConcurrentTaskBase
{
public:
ConcurrentTaskBase(int priority, const std::function<void()>& task)
: m_thread(),
m_active(true)
{
auto wrap = [this](int priority, const std::function<void()>& task)
{
//Unrelated pthread stuff that I commented out
sched_param param{priority};
int err = pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);
if (err)
std::cout << "failed to set new priority: " << err << std::endl;
task();
};
m_thread = std::thread(wrap, priority, task);
}
virtual ~ConcurrentTaskBase(void)
{
waitForCompletion();
}
void waitForCompletion(void)
{
if (m_active)
{
m_thread.join();
m_active = false;
}
}
private:
std::thread m_thread;
bool m_active;
};
template<class R, class... ArgTypes>
class ConcurrentTask;
template<class R, class... ArgTypes>
class ConcurrentTask<R(ArgTypes...)> : public ConcurrentTaskBase
{
public:
ConcurrentTask(int priority, const std::function<R(ArgTypes...)>& task, ArgTypes&&... args)
: ConcurrentTaskBase(priority, bindTask(task, std::forward<ArgTypes>(args)...))
{}
std::shared_ptr<R> getReturn(void) noexcept
{
waitForCompletion();
return m_storage;
}
private:
std::function<void(void)> bindTask(const std::function<R(ArgTypes...)>& task, ArgTypes&&... args)
{
auto params = std::make_tuple(args...);
return [this, task, params](){m_storage = std::make_shared<R>(apply(task, params));};
};
std::shared_ptr<R> m_storage;
};
template<class... ArgTypes>
class ConcurrentTask<void(ArgTypes...)> : public ConcurrentTaskBase
{
public:
ConcurrentTask(int priority, const std::function<void(ArgTypes...)>& task, ArgTypes&&... args)
: ConcurrentTaskBase(priority, bindTask(task, std::forward<ArgTypes>(args)...))
{}
private:
std::function<void(void)> bindTask(const std::function<void(ArgTypes...)>& task, ArgTypes&&... args)
{
auto params = std::make_tuple(args...);
return [this, task, params](){apply(task, params);};
};
};
// Example stuff
struct MyStruct
{
int x;
int y;
};
int testFunction(MyStruct val)
{
std::cout << "X is " << val.x << " Y is " << val.y << std::endl;
return val.x + 10;
}
void printMe(int x)
{
std::cout << "Printing " << x << std::endl;
}
int main()
{
ConcurrentTask<int(MyStruct)> task(20, testFunction, {5, -21});
std::shared_ptr<int> received = task.getReturn();
std::cout << "Return value is " << *received << std::endl;
ConcurrentTask<void(int)> voidTask(25, printMe, -123);
return 0;
}
猜測,bind假定它可以重復調用(在左值上下文中調用時尤其如此!),因此不會將右值參數變成右值參數,並將其綁定函數作為右值參數。 您的代碼要求。 那lambda不是完美的轉發!
您還可以通過lambdas中的引用捕獲const&
std::function
,這只會引起懸而未決的參考地獄。 但這是運行時問題。 作為一般規則&
除非lambda和所有副本的生存期均在當前范圍內終止,否則請不要捕獲。 即使“確定”這不是問題,在原型制作期間也絕對不要這樣做。
我會考慮編寫一個弱版本的std::apply
和index_sequence
並將參數打包到一個tuple
然后進行apply
以apply
其解壓縮到目標可調用對象中。 但這是一個偏見,如果理想的話,那就不要。
這差不多是Yakk寫的。 也許我不太了解您的想法,但對我來說似乎您已經對其進行了過度設計,並且使用std::function
時間過早。 而且, ArgTypes&&
不會是轉發/通用引用的列表,因為它們不是在bindTask
推斷出來的。
以下代碼可在gcc 4.8.2上成功編譯:
為C ++ 11獲取自己的integer_sequence
。 由Xeo提供 。
編寫apply
將元組參數應用於函數(也許可以改進):
template<typename Func, typename Tuple, unsigned int... is>
auto apply_impl(Func&& f, Tuple&& params, seq<is...>)
// -> decltype(f(std::get<is>(std::forward<Tuple>(params))...)) // C++11 only
{
using std::get; // enable ADL-lookup for get in C++14
return f(get<is>(std::forward<Tuple>(params))...);
}
template<typename Func, typename Tuple>
auto apply(Func&& f, Tuple&& params)
// -> decltype(apply_impl(std::forward<Func>(f), std::forward<Tuple>(params),
// GenSeq<std::tuple_size<typename std::decay<Tuple>::type>::value>{}))
// C++11 only
{
return apply_impl(std::forward<Func>(f), std::forward<Tuple>(params),
GenSeq<std::tuple_size<typename std::decay<Tuple>::type>::value>{});
}
簡化您的bindTask
(盡管此時我將其保留為模板):
auto params = make_tuple(args...);
std::function<void(void)> bound = [task,params]{ apply(task, params); };
return bound;
在C ++ 14中,請執行[task=std::move(task),params=std::move(params)]
以避免不必要的復制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.