152

私はファイルを持っています:Base.h

class Base;
class DerivedA : public Base;
class DerivedB : public Base;

/*etc...*/

および別のファイル: BaseFactory.h

#include "Base.h"

class BaseFactory
{
public:
  BaseFactory(const string &sClassName){msClassName = sClassName;};

  Base * Create()
  {
    if(msClassName == "DerivedA")
    {
      return new DerivedA();
    }
    else if(msClassName == "DerivedB")
    {
      return new DerivedB();
    }
    else if(/*etc...*/)
    {
      /*etc...*/
    }
  };
private:
  string msClassName;
};

/*etc.*/

この文字列を実際の型 (クラス) に何らかの形で変換して、BaseFactory がすべての可能な派生クラスを知る必要がないようにし、それぞれに if() を持たせる方法はありますか? この文字列からクラスを生成できますか?

これは、Reflection を使用して C# で実行できると思います。C++に似たようなものはありますか?

4

10 に答える 10

240

いいえ、マッピングを自分で行わない限り、何もありません。C++ には、実行時に型が決定されるオブジェクトを作成するメカニズムがありません。ただし、マップを使用して自分でそのマッピングを行うことができます。

template<typename T> Base * createInstance() { return new T; }

typedef std::map<std::string, Base*(*)()> map_type;

map_type map;
map["DerivedA"] = &createInstance<DerivedA>;
map["DerivedB"] = &createInstance<DerivedB>;

そして、あなたはすることができます

return map[some_string]();

新しいインスタンスを取得します。別のアイデアは、型を自分自身に登録させることです:

// in base.hpp:
template<typename T> Base * createT() { return new T; }

struct BaseFactory {
    typedef std::map<std::string, Base*(*)()> map_type;

    static Base * createInstance(std::string const& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;
        return it->second();
    }

protected:
    static map_type * getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order 
        if(!map) { map = new map_type; } 
        return map; 
    }

private:
    static map_type * map;
};

template<typename T>
struct DerivedRegister : BaseFactory { 
    DerivedRegister(std::string const& s) { 
        getMap()->insert(std::make_pair(s, &createT<T>));
    }
};

// in derivedb.hpp
class DerivedB {
    ...;
private:
    static DerivedRegister<DerivedB> reg;
};

// in derivedb.cpp:
DerivedRegister<DerivedB> DerivedB::reg("DerivedB");

登録用のマクロを作成することができます

#define REGISTER_DEC_TYPE(NAME) \
    static DerivedRegister<NAME> reg

#define REGISTER_DEF_TYPE(NAME) \
    DerivedRegister<NAME> NAME::reg(#NAME)

でも、この2つにはもっと良い名前があると確信しています。ここで使用するのがおそらく理にかなっているもう 1 つのことは、 ですshared_ptr

共通の基底クラスを持たない関連のない型のセットがある場合は、boost::variant<A, B, C, D, ...>代わりに関数ポインターに戻り値の型を指定できます。クラス Foo、Bar、および Baz がある場合のように、次のようになります。

typedef boost::variant<Foo, Bar, Baz> variant_type;
template<typename T> variant_type createInstance() { 
    return variant_type(T()); 
}

typedef std::map<std::string, variant_type (*)()> map_type;

Aboost::variantは労働組合のようなものです。初期化または割り当てに使用されたオブジェクトを調べることで、どのタイプが格納されているかがわかります。ここでそのドキュメントをご覧ください。最後に、生の関数ポインターの使用も少し古いです。最新の C++ コードは、特定の関数や型から分離する必要があります。Boost.Functionより良い方法を探すために調べたいと思うかもしれません。その場合、次のようになります(マップ):

typedef std::map<std::string, boost::function<variant_type()> > map_type;

std::functionを含む C++ の次のバージョンでも利用できるようになりますstd::shared_ptr

于 2009-02-24T16:30:29.393 に答える
6

いいえ、ありません。この問題に対する私の好ましい解決策は、名前を作成方法にマップする辞書を作成することです。このように作成したいクラスは、作成メソッドをディクショナリに登録します。これについては、GoF パターン ブックで詳しく説明しています。

于 2009-02-24T16:08:48.917 に答える
5

短い答えは、あなたができないということです。理由については、これらの SO の質問を参照してください。

  1. C++ にリフレクションがないのはなぜですか?
  2. C++ アプリケーションにリフレクションを追加するにはどうすればよいですか?
于 2009-02-24T16:15:18.883 に答える
4

C++ ファクトリに関する別の SO の質問に回答しました。柔軟な工場に興味がある場合は、そちらをご覧ください。私は、ET++ からマクロを使用する古い方法を説明しようとしています。

ET++は古い MacApp を C++ と X11 に移植するプロジェクトでした。その努力の中で、Eric Gamma などがデザインパターンについて考え始めました

于 2009-02-24T16:10:50.207 に答える
2

boost::functional には非常に柔軟なファクトリ テンプレートがあります: http://www.boost.org/doc/libs/1_54_0/libs/functional/factory/doc/html/index.html

ただし、私の好みは、マッピングとオブジェクト作成メカニズムを隠すラッパー クラスを生成することです。私が遭遇する一般的なシナリオは、いくつかの基本クラスのさまざまな派生クラスをキーにマップする必要があるというものです。この場合、派生クラスはすべて共通のコンストラクター シグネチャを使用できます。これが私がこれまでに思いついた解決策です。

#ifndef GENERIC_FACTORY_HPP_INCLUDED

//BOOST_PP_IS_ITERATING is defined when we are iterating over this header file.
#ifndef BOOST_PP_IS_ITERATING

    //Included headers.
    #include <unordered_map>
    #include <functional>
    #include <boost/preprocessor/iteration/iterate.hpp>
    #include <boost/preprocessor/repetition.hpp>

    //The GENERIC_FACTORY_MAX_ARITY directive controls the number of factory classes which will be generated.
    #ifndef GENERIC_FACTORY_MAX_ARITY
        #define GENERIC_FACTORY_MAX_ARITY 10
    #endif

    //This macro magic generates GENERIC_FACTORY_MAX_ARITY + 1 versions of the GenericFactory class.
    //Each class generated will have a suffix of the number of parameters taken by the derived type constructors.
    #define BOOST_PP_FILENAME_1 "GenericFactory.hpp"
    #define BOOST_PP_ITERATION_LIMITS (0,GENERIC_FACTORY_MAX_ARITY)
    #include BOOST_PP_ITERATE()

    #define GENERIC_FACTORY_HPP_INCLUDED

#else

    #define N BOOST_PP_ITERATION() //This is the Nth iteration of the header file.
    #define GENERIC_FACTORY_APPEND_PLACEHOLDER(z, current, last) BOOST_PP_COMMA() BOOST_PP_CAT(std::placeholders::_, BOOST_PP_ADD(current, 1))

    //This is the class which we are generating multiple times
    template <class KeyType, class BasePointerType BOOST_PP_ENUM_TRAILING_PARAMS(N, typename T)>
    class BOOST_PP_CAT(GenericFactory_, N)
    {
        public:
            typedef BasePointerType result_type;

        public:
            virtual ~BOOST_PP_CAT(GenericFactory_, N)() {}

            //Registers a derived type against a particular key.
            template <class DerivedType>
            void Register(const KeyType& key)
            {
                m_creatorMap[key] = std::bind(&BOOST_PP_CAT(GenericFactory_, N)::CreateImpl<DerivedType>, this BOOST_PP_REPEAT(N, GENERIC_FACTORY_APPEND_PLACEHOLDER, N));
            }

            //Deregisters an existing registration.
            bool Deregister(const KeyType& key)
            {
                return (m_creatorMap.erase(key) == 1);
            }

            //Returns true if the key is registered in this factory, false otherwise.
            bool IsCreatable(const KeyType& key) const
            {
                return (m_creatorMap.count(key) != 0);
            }

            //Creates the derived type associated with key. Throws std::out_of_range if key not found.
            BasePointerType Create(const KeyType& key BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N,const T,& a)) const
            {
                return m_creatorMap.at(key)(BOOST_PP_ENUM_PARAMS(N,a));
            }

        private:
            //This method performs the creation of the derived type object on the heap.
            template <class DerivedType>
            BasePointerType CreateImpl(BOOST_PP_ENUM_BINARY_PARAMS(N,const T,& a))
            {
                BasePointerType pNewObject(new DerivedType(BOOST_PP_ENUM_PARAMS(N,a)));
                return pNewObject;
            }

        private:
            typedef std::function<BasePointerType (BOOST_PP_ENUM_BINARY_PARAMS(N,const T,& BOOST_PP_INTERCEPT))> CreatorFuncType;
            typedef std::unordered_map<KeyType, CreatorFuncType> CreatorMapType;
            CreatorMapType m_creatorMap;
    };

    #undef N
    #undef GENERIC_FACTORY_APPEND_PLACEHOLDER

#endif // defined(BOOST_PP_IS_ITERATING)
#endif // include guard

私は通常、マクロの多用には反対ですが、ここでは例外を設けました。上記のコードは、0 から GENERIC_FACTORY_MAX_ARITY までの N ごとに、GenericFactory_N という名前のクラスの GENERIC_FACTORY_MAX_ARITY + 1 バージョンを生成します。

生成されたクラス テンプレートを使用するのは簡単です。ファクトリが文字列マッピングを使用して BaseClass 派生オブジェクトを作成するとします。派生オブジェクトはそれぞれ、コンストラクターのパラメーターとして 3 つの整数を取ります。

#include "GenericFactory.hpp"

typedef GenericFactory_3<std::string, std::shared_ptr<BaseClass>, int, int int> factory_type;

factory_type factory;
factory.Register<DerivedClass1>("DerivedType1");
factory.Register<DerivedClass2>("DerivedType2");
factory.Register<DerivedClass3>("DerivedType3");

factory_type::result_type someNewObject1 = factory.Create("DerivedType2", 1, 2, 3);
factory_type::result_type someNewObject2 = factory.Create("DerivedType1", 4, 5, 6);

GenericFactory_N クラスのデストラクタは、以下を可能にするために仮想です。

class SomeBaseFactory : public GenericFactory_2<int, BaseType*, std::string, bool>
{
    public:
        SomeBaseFactory() : GenericFactory_2()
        {
            Register<SomeDerived1>(1);
            Register<SomeDerived2>(2);
        }
}; 

SomeBaseFactory factory;
SomeBaseFactory::result_type someObject = factory.Create(1, "Hi", true);
delete someObject;

ジェネリック ファクトリ ジェネレーター マクロのこの行に注意してください。

#define BOOST_PP_FILENAME_1 "GenericFactory.hpp"

ジェネリック ファクトリ ヘッダー ファイルの名前が GenericFactory.hpp であると仮定します。

于 2013-08-15T13:25:00.167 に答える
2

オブジェクトを登録し、文字列名でアクセスするための詳細なソリューション。

common.h:

#ifndef COMMON_H_
#define COMMON_H_


#include<iostream>
#include<string>
#include<iomanip>
#include<map>

using namespace std;
class Base{
public:
    Base(){cout <<"Base constructor\n";}
    virtual ~Base(){cout <<"Base destructor\n";}
};
#endif /* COMMON_H_ */

test1.h:

/*
 * test1.h
 *
 *  Created on: 28-Dec-2015
 *      Author: ravi.prasad
 */

#ifndef TEST1_H_
#define TEST1_H_
#include "common.h"

class test1: public Base{
    int m_a;
    int m_b;
public:
    test1(int a=0, int b=0):m_a(a),m_b(b)
    {
        cout <<"test1 constructor m_a="<<m_a<<"m_b="<<m_b<<endl;
    }
    virtual ~test1(){cout <<"test1 destructor\n";}
};



#endif /* TEST1_H_ */

3. test2.h
#ifndef TEST2_H_
#define TEST2_H_
#include "common.h"

class test2: public Base{
    int m_a;
    int m_b;
public:
    test2(int a=0, int b=0):m_a(a),m_b(b)
    {
        cout <<"test1 constructor m_a="<<m_a<<"m_b="<<m_b<<endl;
    }
    virtual ~test2(){cout <<"test2 destructor\n";}
};


#endif /* TEST2_H_ */

main.cpp:

#include "test1.h"
#include "test2.h"

template<typename T> Base * createInstance(int a, int b) { return new T(a,b); }

typedef std::map<std::string, Base* (*)(int,int)> map_type;

map_type mymap;

int main()
{

    mymap["test1"] = &createInstance<test1>;
    mymap["test2"] = &createInstance<test2>;

     /*for (map_type::iterator it=mymap.begin(); it!=mymap.end(); ++it)
        std::cout << it->first << " => " << it->second(10,20) << '\n';*/

    Base *b = mymap["test1"](10,20);
    Base *b2 = mymap["test2"](30,40);

    return 0;
}

コンパイルして実行します (これは Eclipse で行いました)。

出力:

Base constructor
test1 constructor m_a=10m_b=20
Base constructor
test1 constructor m_a=30m_b=40
于 2015-12-29T13:50:49.747 に答える
1

Tor Brede Vekterli は、求める機能を正確に提供するブースト拡張機能を提供します。現在、現在のブースト ライブラリとの適合は少しぎこちないですが、ベースの名前空間を変更した後、1.48_0 で動作させることができました。

http://arcticinteractive.com/static/boost/libs/factory/doc/html/factory/factory.html#factory.factory.reference

そのようなもの (リフレクションなど) が c++ に役立つ理由を疑問視する人への回答として、UI とエンジン間の対話に使用します。ユーザーが UI でオプションを選択し、エンジンが UI 選択文字列を受け取ります。目的のタイプのオブジェクトを生成します。

ここでフレームワークを使用することの主な利点は (果物リストをどこかに維持するよりも)、登録関数が各クラスの定義に含まれていることです (そして、登録されたクラスごとに登録関数を呼び出すコードは 1 行しか必要ありません)。新しいクラスが派生するたびに手動で追加する必要がある果物リスト。

ファクトリを基本クラスの静的メンバーにしました。

于 2012-02-27T20:03:40.977 に答える
0

これは工場のパターンです。ウィキペディア (およびこの例) を参照してください。悪質なハックなしでは、文字列から型自体を作成することはできません。なぜこれが必要なのですか?

于 2009-02-24T16:09:14.983 に答える
0

Java のようなリフレクションを意味します。ここにいくつかの情報があります: http://msdn.microsoft.com/en-us/library/y0114hz2(VS.80).aspx

一般的に言えば、Google で「c++ リフレクション」を検索します。

于 2009-02-24T16:06:39.013 に答える