4

私は次のことを達成したい:

Entity e;
e.AddComponent<CPosition>(128, 128); //method should instantiate a new CPosition(128,128)
e.AddComponent<CSprite>(some, other, args); //etc

重要な部分はAddComponentメソッドです。渡された引数を使用してジェネリック型を構築しようとする必要があります。引数をコンストラクターに転送するためのC++11の可変個引数テンプレートだと思います。ただし、この機能にはまだアクセスできません(VS2010)。

誰かがこれを行う方法について何か考えがありますか?

4

2 に答える 2

7

それぞれが異なる数のパラメーターをとる一連のオーバーロードを記述します。

class Entity
{
public:
 template<typename T>
 void AddComponent() { component_ = new T(); }

 template<typename T, typename T1>
 void AddComponent(T1 t1) { component_ = new T(t1); }

 template<typename T, typename T1, typename T2>
 void AddComponent(T1 t1, T2 t2) { component_ = new T(t1, t2); }

 // etc
 ...
};
于 2012-10-23T00:05:21.033 に答える
3

boost :: container :: vector :: emplace_backがどのように実装されているかを確認してください: http ://www.boost.org/doc/libs/1_51_0/boost/container/vector.hpp

Boost.Preprocessorを使用して、さまざまな数の引数を取る関数を自動生成します。事前定義された数の関数を生成します。

その結果、各オーバーロードを手作業で作成する必要がありません。代わりに、パターンを1回だけ書き込むことができます。

例えば:

#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>

struct Entity
{
#define ENTITY_PP_PARAM_LIST(z, n, data) const BOOST_PP_CAT(P, n) & BOOST_PP_CAT(p, n)
#define ENTITY_PP_PARAM_PASS(z, n, data) BOOST_PP_CAT(p, n)

#define BOOST_PP_LOCAL_MACRO(n) \
    template<typename GenericType BOOST_PP_ENUM_TRAILING_PARAMS(n, typename P) > \
    void AddComponent(BOOST_PP_ENUM(n, ENTITY_PP_PARAM_LIST, _)) \
    { \
        something=new GenericType(BOOST_PP_ENUM(n, ENTITY_PP_PARAM_PASS, _)); \
    } \
    /**/

#define BOOST_PP_LOCAL_LIMITS (0, 3)
#include BOOST_PP_LOCAL_ITERATE()
};

前処理後、次のように展開されます。

struct Entity
{
    template<typename GenericType  >
    void AddComponent()
    {
        something=new GenericType();
    }

    template<typename GenericType , typename P0 >
    void AddComponent( const P0 & p0)
    {
        something=new GenericType( p0);
    }

    template<typename GenericType , typename P0 , typename P1 >
    void AddComponent( const P0 & p0 , const P1 & p1)
    {
        something=new GenericType( p0 , p1);
    }

    template<typename GenericType , typename P0 , typename P1 , typename P2 >
    void AddComponent( const P0 & p0 , const P1 & p1 , const P2 & p2)
    {
        something=new GenericType( p0 , p1 , p2);
    }
};
于 2012-10-23T00:06:30.803 に答える