0

オブジェクトにメモリを割り当て、任意の引数でそのコンストラクタを呼び出すメモリ アロケータがあります。以下を参照してください。

    // 0 args to constructor
    template <class T>
    inline T* AllocateObject() { return new (InternalAllocate(sizeof(T), alignof(T))) T(); }

    // 1 args to constructor
    template <class T, typename arg0>
    inline T* AllocateObject(const arg0& a0) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0); }

    template <class T, typename arg0>
    inline T* AllocateObject(arg0& a0) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0); }

    // 2 args to constructor
    template <class T, typename arg0, typename arg1>
    inline T* AllocateObject(arg0& a0, arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }

    template <class T, typename arg0, typename arg1>
    inline T* AllocateObject(const arg0& a0, arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }

    template <class T, typename arg0, typename arg1>
    inline T* AllocateObject(arg0& a0, const arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }

    template <class T, typename arg0, typename arg1>
    inline T* AllocateObject(const arg0& a0, const arg1& a1) { return new (InternalAllocate(sizeof(T), alignof(T))) T(a0,a1); }

    //.........

ご覧のとおり、呼び出しの数は引数の数とともに非常に急速に増加します。引数ごとに「const」と「non-const」を交互に使用して、渡した引数で正常に動作するようにする必要があります。(具体的には、値渡しだけでなく参照渡しもできるようにするため)

このスキームを繰り返すよりも、同じタスクを実行するためのより良い方法はありますか? 基本的に、私は最大8〜10個の引数のようなものを見ていますが、それはあまり実現可能ではないと感じています。

ありがとう

4

2 に答える 2

4

可変個引数テンプレートを使用できます。

template <class T, class... Args>
inline T* AllocateObject(Args&&... args) {
    return new (InternalAllocate(sizeof(T), alignof(T)))
               T(std::forward<Args>(args)...);
}

std::forward呼び出しは、すべての参照とネスを保持しますconst


これには C++11 が必要であることに注意してください。最近のほとんどのコンパイラは、可変個引数テンプレートを既にサポートしています (ただし、Microsoft のテンプレートについてはよくわかりません)。

于 2012-08-30T17:53:20.163 に答える
1

テンプレートの解決策ではありませんが、可変引数#defineはこの問題を解決するのに役立ちます。
正確な形式はコンパイラによって異なりますが、MSVC では次のようになります。

#define ALLOCATE_OBJECT(TYPE, ...) \
    ( new( InternalAllocate(sizeof(TYPE), alignof(TYPE)) ) TYPE(__VA_ARGS__) )
于 2012-08-30T18:24:52.977 に答える