Why do I "need opCmp" for an anonymous class? - d

I'm not exactly sure how to explain this, so please ask me to clarify anything that doesn't make sense. I have an interface and a template function which returns functions which return anonymous inner classes based on the compile time argument:
interface MyInterface {
void getName();
}
MyInterface function() getMyInterfaceFactory(string name)() {
return function() {
return new class MyInterface {
void getName() { //Do something involving name here }
};
};
}
Now, getMyInterfaceFactory() used to be getMyInterface() and it used to return the anonymous object directly. Everything worked fine. When I added the the factory functions, I started getting an exception during startup from Object:
object.Exception.....(102): need opCmp for class mymodule.getMyInterfaceFactory!("someargument").getMyInterfaceFactory.__funcliteral14.__anonclass13
So, I looked at the throwing line in the druntime source, and it looks like the default implementation of opCmp for Object just throws. I am not comparing factory functions or MyInterfaces anywhere. I am storing factories as the values of a string indexed associative array, but opCmp was not required when I was storing the anonymous classes directly in that array, only when I started storing the functions. If I insert an opCmp (using memory address), everything seems to work normally, but MyInterface is not really comparable so I'd prefer not to do that unless I have to.
If possible, I'd like to know why/where opCmp is being invoked on the anonymous classes, and how I can prevent or work around it.
Note: The default implementation of opCmp in Object includes a comment vaguely referencing a bug, a commented out memory address comparison, and then the throwing version.
Thanks!
Edit: I should mention, I tried both windbg and ddbg to track down exactly where opCmp was being called, but failed in both cases. Windbg gave no useful information, because it stubbornly refused to load any symbols, ddbg loaded symbols, but the exception occurs during initialization (after static module constructors but before main) and presumably ddbg didn't have access to the druntime symbols?

Update: I'm having trouble reproducing the opCmp error specifically in toy examples, but I think I have figured out what is happening.
It seems that creating anonymous inner classes which inherit interfaces inside of anonymous functions is buggy (go figure). Specifically, the anonymous classes and are not well behaved with respect to virtual functions. Even with opCmp defined, I've had errors with toString and the default constructors, and had members that simply do nothing (but don't throw or error when called). __traits(allMembers, MyInterface) returns the expected information, as does __traits(allMembers, typeof(anonInstance)) but calling the members listed frequently does not work. Weird.
But, if I change the interface to a class with abstract methods, the opCmp error is resolved, the anonymous class behaves as expected, etc. I don't know much about compilers, but I think that during compilation a symbol table is built which maps virtual function names to the memory addresses stored in vtbl. I think what is happening is that the map generated varies when returning an anonymous class derived from an interface. This is possible because interfaces support multiple inheritance, and so can't prescribe an absolute vtbl mapping. Classes, however, could require that all inheritors stick to the same mapping scheme (I don't know if they do, but they could) and so the anonymous classes can't end up with a different mapping.
Again, I'm really not certain, but it seems to fit the symptom, opCmp being called even though I haven't used it anywhere. I don't think it is specifically opCmp that was the problem, I think all the virtual functions defined in Object are vulnerable. I was able to support this with the following:
testopcmphelper.d
interface TestInterface {
string helloWorld();
}
class TestClass {
abstract string helloWorld();
}
testopcmp.d
import testopcmphelper;
import std.stdio;
void invokeFn(TestInterface function() f) {
auto t = f();
auto s = t.helloWorld();
writeln(s);
}
unittest {
auto f = function() {
return new class TestInterface {
string helloWorld() {
return "Hello World!";
}
};
};
invokeFn(f);
}
void invokeFn(TestClass function() f) {
auto t = f();
auto s = t.helloWorld();
writeln(s);
}
unittest {
auto f = function() {
return new class TestClass {
string helloWorld() {
return "Goodbye World!";
}
};
};
invokeFn(f);
}
Which prints:
src.utilities.testopcmp.__unittest2.__funcliteral1.__anonclass10
Goodbye World!
Indicating that invokeFn(TestInterface) is calling Object.toString instead of TestInterface.helloWorld.
I am going to leave the question open for another day, in case I've made a mistake. I will probably then report this as a bug in DMD. I will work around the problem by using only abstract classes for anonymous factory function base types.
TL;DR Seems to be a bug.

Related

How to detect if a class has member variables?

Problem
I would like to detect if a class has member variables and fail a static assert if they do. Something like:
struct b {
int a;
}
static_assert(!has_member_variables<b>, "Class should not contain members"). // Error.
struct c {
virtual void a() {}
void other() {}
}
static_assert(!has_member_variables<c>, "Class should not contain members"). // Fine.
struct d : c {
}
static_assert(!has_member_variables<d>, "Class should not contain members"). // Fine.
struct e : b {
}
static_assert(!has_member_variables<e>, "Class should not contain members"). // Error.
struct f : c {
char z;
}
static_assert(!has_member_variables<f>, "Class should not contain members"). // Error.
Is there a way to achieve this with SFINAE template? This class may have inheritance or even multiple inheritance with virtual functions (no members in the base classes though).
Motivation
I have a pretty simple setup as follows:
class iFuncRtn {
virtual Status runFunc(Data &data) = 0;
};
template <TRoutine, TSpecialDataType>
class FuncRoutineDataHelper : public iFuncRtn {
Status runFunc(Data &data) {
static_assert(!has_member_variables<TRoutine>, "Routines shouldnt have data members!");
// Prepare special data for routine
TSpecialDataType sData(data);
runFuncImpl(sData);
}
class SpecificRtn :
public FuncRoutineDataHelper<SpecificRtn, MySpecialData> {
virtual Status runFuncImpl(MySpecialData &sData) {
// Calculate based on input
sData.setValue(someCalculation);
}
};
The FunctionalityRoutines are managed and run on a per tick basis. They are customized and can perform a wide variety of tasks such as contacting other devices etc. The data that is passed in can be manipulated by the routine and is guaranteed to be passed in on each tick execution until the functionality is finished. The right type of data is passed in based on the DataHelper class. I wan't to discourage future people from mistakenly adding data to the functionality routines as it is very unlikely to do what they expect. To force this, I was hoping to find a way with static assert.
You can solve this by depending on the compiler doing empty base class optimizations, by checking if a class derived from your T has the same size as an empty class with virtual functions:
template<typename T, typename... BaseClasses>
class IsEmpty
{
// sanity check; see the updated demo below
static_assert(IsDerivedFrom<T, BaseClasses...>::value);
struct NonDerived : BaseClasses... { virtual ~NonDerived() = default; };
struct Derived : T { virtual ~Derived() = default; };
public:
inline static constexpr bool value = (sizeof(NonDerived) == sizeof(Derived));
};
This should work with both single and multiple inheritance. However, when using multiple inheritance, it's necessary to list all base classes, like that:
static_assert(IsEmpty<Derived, Base1, Base2, Base3>::value);
Obviously, this solution rules out final classes.
Here's the updated demo.
Here's the original demo. (doesn't work with multiple inheritance)
You will have to mark the classes in some way or another. Pick a way you are comfortable with, a property or some kind of type integer member with an enum. Whoever makes sub-classes will have to follow your convention to make it work.
All other answers here will be some variant of this.
Any answer that uses a sizeof could not guarantee this will work between platforms, compilers, or even classes on the same platform and compiler, due to easily being able to fit a new member inside the default class member alignment, where the sizes of sizeof could easily end up the same for a sub-class.
Background:
As stated in your code and question, all of that is just plain and basic C ad C++ code, and is resolved entirely at compile time. The compiler will tell you if a member exists or not. After its compiled it's a mash of efficient, nameless, machine code with no hints or help for that kind of thing by itself.
Any name you use for a function or data member effectively disappears, as you know it and see it there, after compile and there is no way to lookup any member by name. Each data member is known only by its numerical offset from the top of the class or struct.
Systems like .Net, Java, and others are designed for reflection, which is the ability to remember class members by name, where you can find them at runtime when you program is running.
Templates in C++, unless mixed mode C++ on something like .Net, are also all resolved at compile time, and the names will also all be gone, so the templates by themselves buy you nothing.
Languages like Objective-C also are written to not fail necessarily if certain types of special members are missing, similar to what you are asking, but under the covers its using a lot of supporting code and runtime management to keep track independently, where the actual function itself and its code are still unware and rely on other code to tell them if a member exists or to not fail on null member.
In pure C or C++ you will need to just make your own system, and be literal about tracking dynamically what does what. You could make enums, or lists or dictionaries of name strings. This is what is normally done, you just have to leave hints for yourself. A class cannot be compiled in a way that gives implicit visibility to future sub-classes by definition, without using some form if RTTI.
Its common to put a type member on a class for this very reason, which could be a simple enum. I would not count on sizes or anything that might be platform dependent.

How to write java like argument-level implementation of interface in C++?

One of the nice things in Java is implementing interface. For example consider the following snippet:
interface SimpleInterface()
{
public: void doThis();
}
...
SimpleInterface simple = new SimpleInterface()
{
#Override public doThis(){ /**Do something here*/}
}
The only way I could see this being done is through Lambda in C++ or passing an instance of function<> to a class. But I am actually checking if this is possible somehow? I have classes which implements a particular interface and these interfaces just contain 1-2 methods. I can't write a new file for it or add a method to a class which accepts a function<> or lambda so that it can determine on what to do. Is this strictly C++ limitation? Will it ever be supported?
Somehow, I wanted to write something like this:
thisClass.setAction(int i , new SimpleInterface()
{
protected:
virtual void doThis(){}
});
One thing though is that I haven't check the latest spec for C++14 and I wanted to know if this is possible somehow.
Thank you!
Will it ever be supported?
You mean, will the language designers ever add a dirty hack where the only reason it ever existed in one language was because those designers were too stupid to add the feature they actually needed?
Not in this specific instance.
You can create a derived class that derives from it and then uses a lambda, and then use that at your various call sites. But you'd still need to create one converter for each interface.
struct FunctionalInterfaceImpl : SimpleInterface {
FunctionalInterfaceImpl(std::function<void()> f)
: func(f) {}
std::function<void()> func;
void doThis() { func(); }
};
You seem to think each class needs a separate .h and .cpp file. C++ allows you to define a class at any scope, including local to a function:
void foo() {
struct SimpleInterfaceImpl : SimpleInterface
{
protected:
void doThis() override {}
};
thisClass.setAction(int i , new SimpleInterfaceImpl());
}
Of course, you have a naked new in there which is probably a bad idea. In real code, you'd want to allocate the instance locally, or use a smart pointer.
This is indeed a "limitation" of C++ (and C#, as I was doing some research some time ago). Anonymous java classes are one of its unique features.
The closest way you can emulate this is with function objects and/or local types. C++11 and later offers lambdas which are semantic sugar of those two things, for this reason, and saves us a lot of writing. Thank goodness for that, before c++11 one had to define a type for every little thing.
Please note that for interfaces that are made up of a single method, then function objects/lambdas/delegates(C#) are actually a cleaner approach. Java uses interfaces for this case as a "limitation" of its own. It would be considered a Java-ism to use single-method interfaces as callbacks in C++.
Local types are actually a pretty good approximation, the only drawback being that you are forced to name the types (see edit) (a tiresome obligation, which one takes over when using static languages of the C family).
You don't need to allocate an object with new to use it polymorphically. It can be a stack object, which you pass by reference (or pointer, for extra anachronism). For instance:
struct This {};
struct That {};
class Handler {
public:
virtual ~Handler ();
virtual void handle (This) = 0;
virtual void handle (That) = 0;
};
class Dispatcher {
Handler& handler;
public:
Dispatcher (Handler& handler): handler(handler) { }
template <typename T>
void dispatch (T&& obj) { handler.handle(std::forward<T>(obj)); }
};
void f ()
{
struct: public Handler {
void handle (This) override { }
void handle (That) override { }
} handler;
Dispatcher dispatcher { handler };
dispatcher.dispatch(This {});
dispatcher.dispatch(That {});
}
Also note the override specifier offered by c++11, which has more or less the same purpose as the #Override annotation (generate a compile error in case this member function (method) does not actually override anything).
I have never heard about this feature being supported or even discussed, and I personally don't see it even being considered as a feature in C++ community.
EDIT right after finishing this post, I realised that there is no need to name local types (naturally), so the example becomes even more java-friendly. The only difference being that you cannot define a new type within an expression. I have updated the example accordingly.
In c++ interfaces are classes which has pure virtual functions in them, etc
class Foo{
virtual Function() = 0;
};
Every single class that inherits this class must implement this function.

std::map::insert exception

This is another, "My code isn't working and i don't know why, " question i'm afraid. I just don't have enough knowledge of the stl to know why std::map::insert would throw an exception. If you know what cases it throws an exception, you can probably skip this wall of text and just answer. If you just desperately need some background on the issue, then have at it. I'll post my code and explain what is done, and i would be very grateful if all you with a better knowledge of the stl could explain what could be wrong with my call to insert.
I wrote an object awhile ago that i use occasionally as my go to factory object. It's main purpose is basically to take a string and store both the string and a "create new object function" pointer, so that in the end, you can call a function, pass a string, and if there is a valid registration for it, it returns a new instance of a derived object. Less talk, more code, here's what i got:
factory.h
#ifndef FACTORY_H
#define FACTORY_H
// library tools
#include <map>
#include <string>
// Simplified registration macros
#define DECLARE_DERIVED(T, base) static Factory<base>::DerivedRegister<T> reg;
#define DEFINE_DERIVED(T, base, s) Factory<base>::DerivedRegister<T> T::reg(s);
template<class base>
class Factory
{
protected:
template<class T>
static base * createT() { return new T;}
public:
typedef std::map<std::string, base*(*)()> map_type;
virtual ~Factory(){ }
static base * createInstance(const std::string & s)
{
if(!m_Map.count(s))
return nullptr;
std::map<std::string, base*(*)()>::iterator it = m_Map.find(s);
return it->second();
}
template <class T>
struct DerivedRegister;
protected:
static map_type m_Map;
};
template<class base>
template<class T>
struct Factory<base>::DerivedRegister : public Factory<base>
{
DerivedRegister(std::string const & s)
{
m_Map.insert(std::pair<std::string, base*(*)()>(s, &createT<T>));
}
};
#endif
here's a better explanation of what it does real quick. Let's say you have a base class, class A . and then you have any number of derived classes. I make a factory object somewhere templated to A, and then either create a derived register object manually, or use the macro at the top within the derived classes declaration to create a static registry object. Then you define it in the implementation and call it's constructor, passing in a string to be used to identify the object. using the factory member createInstance you can pass in a string identifier and have a derived object returned, pointed to by an A *.
example:
A.h
class A
{
};
A.cpp
// the map for this factory template has to be defined somewhere, as it is static
Factory<A>::map_type Factory<A>::m_Map;
b.h
#include <A.h>
class B : public A
{
// anywhere in declaration of derived B
DECLARE_DERIVED(A, B)
};
b.cpp
// just somewhere in cpp file
DEFINE_DERIVED(A, B, "B")
main.cpp
int main()
{
A * ptr;
Factory<A> factory;
ptr = factory.createInstance("B");
}
This object has worked for me in the past, mostly without a hitch. Now i'm doing a project a little more complicated. I've taken a liking to the data organization/ api design involved with game engines, and i'm just trying to implement a solution of cataloging, (but not instantiated) shaders, so that you have a whole list of the shaders you've programmed, but they will not be instantiated at run-time unless needed. That aside, this question actually has nothing to do with d3d11, or at least i hope not.
So here is what's going on. I have an object that represents a graphics-shader abstract class. All the shaders you wish to write must derive from this object. The you derive from and implement it's functions differently for all your different shaders.
let's call the base object "SYNC::D3D11Shader" in namespace sync and the derived shaders "ColorShader" "LightShader" and "TextureShader". Since i do not simply want to make an std::map of instances of these shaders within the rendering object, i make a factory within the rendering object like this.
D3D11Renderer.h
class D3D11Renderer
{
// many other members...
Factory<D3D11Shader> m_ShaderFactory;
// many other member...
};
D3D11Renderer.cpp
// define this templated classes map or you'll get undefined errors
Factory<SYNC::D3D11Shader>::map_type Factory<SYNC::D3D11Shader>::m_Map;
and then in the ColorShader i use the macros like so
D3D11ColorShader.h
class D3D11ColorShader : public SYNC::D3D11Shader
{
// ...lotsa members
DECLARE_DERIVED(D3D11ColorShader, SYNC::D3D11Shader)
// lotsa member...
};
D3D11ColorShader.cpp
// define the registery object with it's key here
DEFINE_DERIVED(D3D11ColorShader, SYNC::D3D11Shader, "ColorShader")
this all compiles fine, and where it throws it's exception is where i first call the registryObjects constructor in D3D11ColorShader.cpp, spefically at the insert call. the exception error is this:
Unhandled exception at 0x772315de in Syncopate.exe: 0xC0000005: Access
violation reading location 0x00000004.
So in reality, the question boils down to, when does std::map::insert throw an exception and why. I just knew everyone would be asking for some background on what i'm doing. Low and behold, a giant wall of text has appeared! All i really need is a hunch.
also should i or should i not tag d3d11, because the question doesn't really pertain to it?
Here's a problem:
std::map<std::string, base*(*)()>::iterator it = m_Map.find(s);
return it->second();
if the call to find fails (i,e. it can't find 's' in the map), then it will return m_Map.end(). Dereferencing that is a no-no.
My guess would be that this is due to the order of initialization of static variables. There is no way to control this order. So you are not guaranteed that your initialization:
Factory<A>::map_type Factory<A>::m_Map;
gets called before this initialization:
DEFINE_DERIVED(A, B, "B")
In this case the latter statement must be getting initialized first and so you map has not been allocated.
An alternative design pattern would control the initialization of the singleton factories. If you have an explicit Initialize function on each which creates the factory object then you can call this at the start of your main. E.g.
Factory.h
class Factory {
private:
static Factory* instance_;
public:
static Initialize(){instance_=new Factory;}
Factory* instance(){return instance_;}
}
Factory.cpp
static Factory* Factory::instance_ = NULL;
If you have a lot of factories you will probably want a single initialize function that initializes them all, and you will have to remember to add in the new factories as you create them.
Okay, i have actually been laboring over this error for about a day, and only now do i realize what is wrong.
problem 1:
the derived shaders header was never actually included anywhere throughout the project, and despite the fact that it never needs to be directly instantiated, it still has to be included somewhere so it can be linked and included in build.
problem 2:
interesting enough, just like combinatorial said, the initialization order was not done one after the other, but then looking over my old code, it seemed to initialize correctly before. what the difference here was, i put the factory of the derived objects within a different object then the base class. what i used to do was declare a static function and static factory within the base class so that you could instantiate any of it's registered derived classes from the base class itself. When the factory is included within the base class instead, and instantiation is done through a static function, the initialization order of all the statics seems to be constently in order ( not sure if this is always true). It runs fine now after changing this.
so now, my answer, you can get operating system exceptions like this for trying to use references to objects that were never actually included anywhere in your project. I don't have a very good knowledge of compilers or linkers to tell you why it seemed to compile fine, despite this object never being included. If someone wants to extend my answer, please.
I use MSVC++ 2010 express if that pertains to this predicament.

Copying Methods from Member

I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.

Possible to instantiate object given its type in C++?

I've been programming in Java way too long, and finding my way back to some C++. I want to write some code that given a class (either a type_info, or its name in a string) can create an instance of that class. For simplicity, let's assume it only needs to call the default constructor. Is this even possible in C++, and if not is it coming in a future TR?
I have found a way to do this, but I'm hoping there is something more "dynamic". For the classes I expect to wish to instantiate (this is a problem in itself, as I want to leave that decision up to configuration), I have created a singleton factory with a statically-created instance that registers itself with another class. eg. for the class Foo, there is also a FooFactory that has a static FooFactory instance, so that at program startup the FooFactory constructor gets called, which registers itself with another class. Then, when I wish to create a Foo at runtime, I find the FooFactory and call it to create the Foo instance. Is there anything better for doing this in C++? I'm guessing I've just been spoiled by rich reflection in Java/C#.
For context, I'm trying to apply some of the IOC container concepts I've become so used to in the Java world to C++, and hoping I can make it as dynamic as possible, without needing to add a Factory class for every other class in my application.
You could always use templates, though I'm not sure that this is what your looking for:
template <typename T>
T
instantiate ()
{
return T ();
}
Or on a class:
template <typename T>
class MyClass
{
...
};
Welcome in C++ :)
You are correct that you will need a Factory to create those objects, however you might not need one Factory per file.
The typical way of going at it is having all instanciable classes derive from a common base class, that we will call Base, so that you'll need a single Factory which will serve a std::unique_ptr<Base> to you each time.
There are 2 ways to implement the Factory:
You can use the Prototype pattern, and register an instance of the class to create, on which a clone function will be called.
You can register a pointer to function or a functor (or std::function<Base*()> in C++0x)
Of course the difficulty is to register those entries dynamically. This is typically done at start-up during static initialization.
// OO-way
class Derived: public Base
{
public:
virtual Derived* clone() const { return new Derived(*this); }
private:
};
// start-up...
namespace { Base* derived = GetFactory().register("Derived", new Derived); }
// ...or in main
int main(int argc, char* argv[])
{
GetFactory().register("Derived", new Derived(argv[1]));
}
// Pointer to function
class Derived: public Base {};
// C++03
namespace {
Base* makeDerived() { return new Derived; }
Base* derived = GetFactory().register("Derived", makeDerived);
}
// C++0x
namespace {
Base* derived = GetFactory().register("Derived", []() { return new Derived; });
}
The main advantage of the start-up way is that you can perfectly define your Derived class in its own file, tuck the registration there, and no other file is impacted by your changes. This is great for handling dependencies.
On the other hand, if the prototype you wish to create requires some external information / parameters, then you are forced to use an initialization method, the simplest of which being to register your instance in main (or equivalent) once you have the necessary parameters.
Quick note: the pointer to function method is the most economic (in memory) and the fastest (in execution), but the syntax is weird...
Regarding the follow-up questions.
Yes it is possible to pass a type to a function, though perhaps not directly:
if the type in question is known at compile time, you can use the templates, though you'll need some time to get acquainted with the syntax
if not, then you'll need to pass some kind of ID and use the factory approach
If you need to pass something akin to object.class then it seems to me that you are approaching the double dispatch use case and it would be worth looking at the Visitor pattern.
No. There is no way to get from a type's name to the actual type; rich reflection is pretty cool, but there's almost always a better way.
no such thing as "var" or "dynamic" in C++ last time I've checked(although that was a WHILE ago). You could use a (void*) pointer and then try casting accordingly. Also, if memory serves me right, C++ does have RTTI which is not reflection but can help with identifying types at runtime.