Skip to content

Instantly share code, notes, and snippets.

@iwadon
Created October 30, 2012 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwadon/3978585 to your computer and use it in GitHub Desktop.
Save iwadon/3978585 to your computer and use it in GitHub Desktop.
CppUnitを真似てファクトリーの登録を分離できるようにしたけど、登録部分をライブラリにしちゃうと当然のごとくリンクされなくて泣ける。どうしたものか。
#ifndef BASE_HH_INCLUDED
#define BASE_HH_INCLUDED 1
struct Base
{
virtual const char *ClassName() const
{
return "Base";
}
};
#endif // !defined(BASE_HH_INCLUDED)
#ifndef BASE_FACTORY_HH_INCLUDED
#define BASE_FACTORY_HH_INCLUDED 1
#include "base.hh"
class BaseFactoryRegistry
{
public:
void RegisterFactory(Base *(*factory)())
{
factory_ = factory;
}
Base *NewBase()
{
return (factory_)();
}
static BaseFactoryRegistry *Instance()
{
static BaseFactoryRegistry instance;
return &instance;
}
private:
Base *(*factory_)();
};
#endif // !defined(BASE_FACTORY_HH_INCLUDED)
#include "derived.hh"
#include "base_factory_registry.hh"
struct BaseFactoryRegistration_Derived
{
BaseFactoryRegistration_Derived()
{
BaseFactoryRegistry::Instance()->RegisterFactory(NewDerived);
}
static Base *NewDerived()
{
return new Derived;
}
};
BaseFactoryRegistration_Derived base_factory_registration_derived;
#ifndef DERIVED_HH_INCLUDED
#define DERIVED_HH_INCLUDED
#include "base.hh"
struct Derived : public Base
{
const char *ClassName() const
{
return "Derived";
}
};
#endif // !defined(DERIVED_HH_INCLUDED)
#include "base_factory_registry.hh"
#include <iostream>
int main()
{
Base *base = BaseFactoryRegistry::Instance()->NewBase();
std::cout << base->ClassName() << std::endl;
return 0;
}
CXX = g++
CXXFLAGS = -Wall -O2 -g
CPPFLAGS =
AR = ar
LD = g++
LDFLAGS =
LIBS =
RM = rm -f
all: ok ng
clean:
$(RM) ok ng
$(RM) libderived.a
$(RM) main.o derived.o
ok: main.o derived.o
$(LD) $(LDFLAGS) -o $@ main.o derived.o
ng: main.o libderived.a
$(LD) $(LDFLAGS) -o $@ main.o -L. -lderived
main.o: main.cc
$(CXX) $(CXXFLAGS) -o $@ -c $<
derived.o: derived.cc
$(CXX) $(CXXFLAGS) -o $@ -c $<
libderived.a: derived.o
$(RM) $@; $(AR) crs $@ derived.o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment