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.
Related
Introduction
I've got a library, which registers a bunch of metatypes, illustrated by this code:
abstractfoobase.h
namespace foo {
enum FooState { OK, MAYBE };
class AbstractFooBase : public QObject {...};
}
Q_DECLARE_METATYPE(foo::FooState)
There is also a corresponding abstractfoobase.cpp, contents depending on what exactly is implemented in base class.
foousingclass.h:
namespace foo {
class FooUsingClass : public AbstractFooBase {...};
}
Again there is corresponding foousingclass.cpp, which has method implementations etc.
Now, that Q_DECLARE_METATYPE enables the type for Qt template classes and QVariant. To enable using the type in queued signals and such, there also needs to be a corresponding call:
qRegisterMetaType<foo::FooState>();
Question
What is(are) the good place(s) to put the qRegisterMetaType call? I obviously don't want any expllicit initialization call from application code. The registrations must have happened after doing a foo::FooUsingClass *f = new foo::FooUsingClass();.
In Java I'd put this kind of code in a static initialization block. I can see several ways to do this in C++ too, but none of them seem particularily nice. For example, simply putting these to AbstractFooBase constructor will cause the registrations being called every time a subclass instance is created, which may be undesired overhead. So those who have done this, where did you put the qRegisterMetaType calls?
I've recently discovered a simple solution, which works with static libraries as well.
It exploits the fact that qMetaTypeId<>() is used throughout Qt's meta type system. So, with an explicit template instantiation, we can enforce linkage to abstractfoobase.cpp (otherwise the linker might decide not to if there are no referenced symbols) and ensure that the type is registered statically at program startup:
abstractfoobase.h
#include <QMetaType>
namespace foo {
enum FooState { OK, MAYBE };
}
Q_DECLARE_METATYPE(foo::FooState)
extern template int qMetaTypeId<foo::FooState>();
abstractfoobase.cpp
static const int kFooStateMetaTypeId = qRegisterMetaType<foo::FooState>();
template int qMetaTypeId<foo::FooState>();
I can imagine something as following:
in abstractfoobase.cpp:
namespace foo {
/// Initializer
class FooStateInit {
public:
FooStateInit() {
qRegisterMetaType<foo::FooState>();
}
};
static FooStateInit fooStateInit;
} // namespace foo
If your type will be instantiated frequently, you could use a function static initialization in the constructor:
struct OftenInstantiatedDataType
{
OftenInstantiatedDataType()
{
static const int reg = qRegisterMetaType<OftenInstantiatedDataType>();
}
};
Q_DECLARE_METATYPE(OftenInstantiatedDataType);
Pros:
Lazy registration - will only be called if your type is instantiated at all
Single registration - will only be called once, no matter how often your type is instantiated
Cons:
Makes executable larger
In the few apps I created I used to simply register them in main()-like function that defines the application's startup. Of course, that separates the registration from the .cpp/.h file, but in turn it guarantees that I will not fall into some name-collisions (I see all names/types in one place) and also guarantees that the regs are done exactly one single time: app startup ;)
But, that's not a.. 'handy' way.. if anyone has better way, I'd like to see it too.
I am trying to write an application that is loading its extensions dynamically during runtime. I used Boost Preprocessor library to write a preprocessor function that, given a list of names, declares a class for each name (and make all of them subclasses of some AbstractPlugin class) and then declares a Boost MPL sequence containing that classes. Then I wrote a class that tries a pointer to AbstractPlugin if it could be cast to any of the types in that MPL sequence.
The problem here is that my preprocessor function needs a full list of all extensions I want to create and load. Is there some technique that lets me register each extension in a separate file?
Update:
I believe, my explanation of situation was too vague, so I decided to make it more specific.
I would like to define a collection of extension types. For each extension type there could be any number of extensions. During runtime the program loads external library, resolve the entry point function, call it and, as a result, get a pointer. Then it tries to cast that pointer to all registered extension types (using dynamic_cast, so classes for extension types all inherit from some polymorphic base class). If a cast to some extension type succeeds, the casted pointer is used in a call to special handler for that extension type.
The number of extension types is known at compile time (while, obviously, the number of extensions is infinite). Using my aproach the loader class uses this knowledge to check whether there exists a handler for each extension type (if not, the program doesn't compile). Also, my aproach doesn't force classes for extension types know anything about the loader (so it is easy to modify the loader). But it would be more convenient if each extension type registered itself.
You can make all your classes self-registering in some sort of collection. Here's a skeleton approach:
Base.hpp:
#include <memory>
#include <unordered_map>
#include <string>
struct Base
{
virtual ~Base() = default;
using create_f = std::unique_ptr<Base>();
static void registrate(std::string const & name, create_f * fp)
{
registry()[name] = fp;
}
static std::unique_ptr<Base> instantiate(std::string const & name)
{
auto it = registry().find(name);
return it == registry().end() ? nullptr : (it->second)();
}
template <typename D>
struct Registrar
{
explicit Registrar(std::string const & name)
{
Base::registrate(name, &D::create);
}
// make non-copyable, etc.
};
private:
static std::unordered_map<std::string, create_f *> & registry();
};
Base.cpp:
#include "Base.hpp"
std::unordered_map<std::string, Base::create_f *> & Base::registry()
{
static std::unordered_map<std::string, Base::create_f *> impl;
return impl;
}
Now to use this in a client:
Derived.hpp:
#include "Base.hpp"
struct Derived : Base
{
static std::unique_ptr<Base> create() { return std::make_unique<Derived>(); }
// ...
};
Derived.cpp:
#include "Derived.hpp"
namespace
{
Base::Registrar<Derived> registrar("MyClass");
}
The constructor of the Base::Registrar<Derived> takes care of registering the class Derived under the name "MyClass". You can create instances of Derived dynamically via:
std::unique_ptr<Base> p = Base::instantiate("MyClass");
The code could/should be improved by detecting repeat registrations, printing a list of available classes, etc. Note how we avoid any static initialization ordering problems my making the actual registry map object a block-static object, which is guaranteed to be initialized before its first use, and thus destroyed only after its last use.
It is not difficult to implement such an extension framework using the abstract factory pattern.
http://en.wikipedia.org/wiki/Abstract_factory_pattern
You can register those abstract factory functions/objects in a global list, and do whatever you want to do base on it.
As it turns out what I want is impossible. The reason for that is "register" in this context means "put a type inside type sequence" and type sequences are immutable because they are types themselves. So one should either create this type sequence manually, or as some people suggested move the "registration" into runtime.
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.
Inside of a static member function I need to get the type.
class MyClass
{
public:
static void myStaticFunc();
...
};
And then in the implementation I want to have:
void MyClass::myStaticFunc()
{
// Get MyClass as a type so I can cast using it
(get_type_from_static_function()*)someOtherVariable;
}
Is this even possible? Normally I would use something from typeinfo on an object but I don't have this to work with.
I do not want to just use (MyClass*) because this is going inside of a macro and I'd like to keep it as simple as possible so that it can be called without a class name.
If it helps I am using QT but I couldn't find any macros to get the current class. It doesn't necessarily need to be programmatic - it can be a macro.
Cheers!
EDIT:
Here is the actual macro function:
#define RPC_FUNCTION(funcName) \
static void rpc_##funcName(void* oOwner, RpcManager::RpcParamsContainer params){ ((__class__*)oOwner)->funcName(params); }; \
void funcName(RpcManager::RpcParamsContainer params);
I then call RPC_FUNCTION(foo) in a class declaration. I want __class__ to be whatever class declaration I am in. I'm well aware I can just add className after funcName but I want to keep this as simple as possible when actually using it. My RPC manager calls rpc_foo and passes a pointer to an object of the class I declared it in. Essentially I need to know how to determine the actual class of that void* parameter.
In Visual Studio 2012 you can use that trick, but it will not work in gcc, at least for now.
template<typename base_t>
static auto GetFunctionBaseType(void(base_t::*)())->base_t;
struct TBase
{
template<typename T> void GetBaseType();
typedef decltype(GetFunctionBaseType(&GetBaseType<void>)) this_t;
static void rpc_func1(void * ptr)
{
((this_t*)ptr)->func1();
}
};
I believe that what you're asking for at heart is simply not possible: C++ is a statically typed language, which means that all type information must be available at compile time (runtime polymorphism notwithstanding). That is, when you say,
T x;
then the type T must be known at compile time. There is no such thing as "T_from_user() x;", whereby the actual type of a variable is determined at runtime. The language just isn't designed that way.
Usually if you're asking such a question that's an indicator that you're going about a problem the wrong way, though. Typical solutions for polymorphic situations involve class inheritance and virtual functions, or other sorts of lookup tables, or really any number of different approaches. Your request for a preprocessor macro also indicates that something is off. Any programming language has its idioms, and veering too far from those is usually a bad idea.
What you want to do is called Reflection. It was implemented in .NET (I don't know, maybe in Java too) and is going to be implemented in future standards of C++.
It seems you have a few unrelated classes that have a number of methods in common (the ones that can be sent as the funcName argument in your example).
Instead of having these unrelated classes, consider a polymorphic approach. For example, let's say the functions that you support are func1 and func2, then you can work this out in this way:
class BaseClass {
public:
virtual void func1(RpcManager::RpcParamsContainer args) = 0;
virtual void func2(RpcManager::RpcParamsContainer args) = 0;
};
class MyClass1 : public BaseClass {
public:
virtual void func1(RpcManager::RpcParamsContainer args) { /* func1 implementation here */ }
virtual void func2(RpcManager::RpcParamsContainer args) { /* func2 implementation here */ }
};
class MyClass2 : public BaseClass {
public:
virtual void func1(RpcManager::RpcParamsContainer args) { /* func1 implementation here */ }
virtual void func2(RpcManager::RpcParamsContainer args) { /* func2 implementation here */ }
};
With the above design your can pass a BaseClass* around, and you can call func1 or func2 without having to do any casts, and the compiler will find the correct version to invoke. For example, in your macro you could do something like this:
#define RPC_FUNCTION(funcName) static void rpc_##funcName(BaseClass* oOwner, RpcManager::RpcParamsContainer params){ oOwner->funcName(params); };
I hope this helps!
Are searching for the function macro? It's a macro that expands to the current function name.
__FUNCTION__
No, a static method can only see static members of the class. It doesn't make sense for it to access instance members (as in, standard variables etc) as they don't exist unless the class has been instantiated.
It seems like you want something like the Singleton design pattern. This allows for only a single instance of the class to exist at a time.
Another way would be to have a static list of all instances of a class, then in the class constructor, add the this pointer to that list. As I say though, static members cannot access instance variables, as they may not exist at all.
I suppose the greater question is this: why do you need to access an instance variable from a static member? If you require access to an instance member, you should be calling the function in the context of the current instance, otherwise you're breaking the OOP paradigm pretty hard.
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.