所有権を共有するネストされたオブジェクトへのポインタを、包含するオブジェクトにstd::shared_ptr
で渡すことができます。このネストされたオブジェクトが配列であることを起こる、あなたは配列型としてアクセスしたい場合は、実際には、適切なT
とN
でT[N]
を使用する必要があります。上記のコードq
で
#include <functional>
#include <iostream>
#include <iterator>
#include <memory>
#include <queue>
#include <utility>
#include <vector>
using queue = std::queue<std::function<void()>>;
template <typename T>
struct is_range {
template <typename R> static std::false_type test(R*, ...);
template <typename R> static std::true_type test(R* r, decltype(std::begin(*r))*);
static constexpr bool value = decltype(test(std::declval<T*>(), nullptr))();
};
template <typename T>
std::enable_if_t<!is_range<T>::value> process(T const& value) {
std::cout << "value=" << value << "\n";
}
template <typename T>
std::enable_if_t<is_range<T>::value> process(T const &range) {
std::cout << "range=[";
auto it(std::begin(range)), e(std::end(range));
if (it != e) {
std::cout << *it;
while (++it != e) {
std::cout << ", " << *it;
}
}
std::cout << "]\n";
}
template <typename P, typename T>
std::function<void()> make_fun(P const& p, T& value) {
return [ptr = std::shared_ptr<T>(p, &value)]{ process(*ptr); };
// here ----^
}
template <typename T, typename... M>
void enqueue(queue& q, std::shared_ptr<T> const& ptr, M... members) {
(void)std::initializer_list<bool>{
(q.push(make_fun(ptr, (*ptr).*members)), true)...
};
}
struct foo {
template <typename... T>
foo(int v, T... a): value(v), array{ a... } {}
int value;
int array[3];
std::vector<int> vector;
};
int main() {
queue q;
auto ptr = std::make_shared<foo>(1, 2, 3, 4);
enqueue(q, ptr, &foo::value, &foo::array, &foo::vector);
while (!q.empty()) {
q.front()();
q.pop();
}
}
だけのシンプルなstd::queue<std::function<void()>>
ですが、私はあなたが別のスレッドに処理をオフロードするスレッドプールであるかもしれないと想像できることを願っています。実際にスケジュールされた処理も簡単ですが、実際にはかなりの量の作業であると想像していただければ幸いです。
あなたの悪用を防ぐものはありませんが、一度 'shared_ptr'をお持ちでしたら、追加情報なしでその要素を反復処理することができます。 'new T [N]'からポインタを取得しようとしているので、最初の要素へのポインタでそれを構築します。 –
@KerrekSB "... *新しい*' T [N] 'からポインタを取得すると思われるので、必ずしもそうではありません。 [私の答え](http://stackoverflow.com/a/40447905/6394138)を参照してください。 – Leon
さらにN4082を見てきましたが、 'operator []'は 'i