1

make_pairは、タイプに言及せずにペアを作成できます。クラスに同じトリックを使用したいのですが、boost :: noncopyableを継承しているため、コンパイルされません。

template<class Iter>
struct bit_writer : boost:noncopyable
{
    Iter iter;
    bit_writer(Iter iter)
    : iter(iter)
    {}
};

template<class Iter>
bit_writer<Iter> make_bit_writer(Iter iter)
{
    return bit_writer<Iter>(iter);
}
vector<char> vec;
auto w = make_bit_writer(vec);

別の方法はありますか?make_bit_writerを友達にしてみたところ、アイデアが足りなくなってしまいました。

4

2 に答える 2

4

C ++ 11を使用している場合は、次のようなものを使用してこれを行うことができます。

#include <functional>
#include <utility>
#include <type_traits>

struct noncopyable_but_still_moveable {
  noncopyable_but_still_moveable(const noncopyable_but_still_moveable&) = delete;
  noncopyable_but_still_moveable(noncopyable_but_still_moveable&&) = default;
  noncopyable_but_still_moveable() = default;
  noncopyable_but_still_moveable& operator=(const noncopyable_but_still_moveable&) = default;
  noncopyable_but_still_moveable& operator=(noncopyable_but_still_moveable&&) = default;
};

template <typename T>
struct test : noncopyable_but_still_moveable {
  test(T) {}
  // the rest is irrelevant 
};

template <typename T>
test<T> make_test(T&& val) {
  return test<typename std::remove_reference<T>::type>(std::forward<T>(val));
}

int main() {
  auto && w = make_test(0);
}

boost::noncopyableコピーコンストラクターが削除された型に置き換えたことに注意してください。これは、コピー不可能なものを作成するC ++ 11の方法であり、ブーストクラスも移動できないために必要です。もちろん、それをクラス自体の中に入れて、それ以上継承しないようにすることもできます。

C ++ 11がない場合は、Boostmoveなどを使用してこれらのセマンティクスをエミュレートする必要があります。

于 2012-07-27T21:19:09.263 に答える
2

C ++ 11が必要になり、移動セマンティクス用にクラスを更新する必要があります。提案された問題に対する他の解決策はありません。

class test {
public:
    test(test&&);
    // stuff
};
test make_test(...) {
    return test(...);
}
int main() {
    // Both valid:
    auto p = make_test(...);
    auto&& p2 = make_test(...);
} 
于 2012-08-01T17:50:06.903 に答える