我的问题类似于这些,但似乎并没有完全相关:
我得到的是这样的:
struct thingy;
struct container
{
static container& instance(); // singleton
int register_thingy(thingy*);
};
struct thingy
{
virtual ~thingy() {}
virtual int id() const = 0;
};
//template trick to force registration.
template < typename Derived >
struct registered_thingy : thingy
{
registered_thingy() : my_id(my_static_id) {}
int id() const { return my_id; }
private:
int my_id;
static int my_static_id;
}
template < typename Derived >
int registered_thingy<Derived>::my_static_id =
container::instance().register_thingy(new Derived);
Run Code Online (Sandbox Code Playgroud)
现在,concrete_thingy.cpp我在一个文件中:
struct my_concrete_thingy : registered_thingy<my_concrete_thingy> …Run Code Online (Sandbox Code Playgroud)