Related
So I would like to extend the factory method to a templated class with registry.
I have the following code. It compiles with g++ but does not register the templated class
#include <iostream>
#include <memory>
#include <string>
#include <map>
template<class T>
class car
{
public:
car(){}
virtual ~car(){}
virtual void foo() = 0;
T var;
};
template<class T>
class Factory
{
public:
typedef car<T>* (*createObj)(void);
static bool checkIn(const std::string& name, createObj funcCreate)
{
if(storage.find(name) == storage.end())
{
storage[name] = funcCreate;
return true;
}
return false;
}
static car<T>* create(const std::string& name)
{
auto it = storage.find(name);
if (it != storage.end())
{
return it->second();
}
return nullptr;
}
private:
static std::map<std::string, createObj> storage;
};
template<class T>
std::map<std::string, typename Factory<T>::createObj> Factory<T>::storage;
template<class T>
class car1
:public car<T>
{
public:
car1(){}
static car<T>* create()
{
return new car1;
}
static std::string name() { return "car1"; }
virtual void foo(){std::cout << "I am car1 " << std::endl;}
private:
static bool checkedIn;
};
template<class T>
bool car1<T>::checkedIn = Factory<T>::checkIn(car1::name(), car1::create);
int main()
{
car<double>* obj1 = Factory<double>::create("car1");
obj1->foo();
delete obj1;
obj1=nullptr;
return 0;
}
What is needed to make it register?
The end results is expected to be something like what is reported in the main function.
Is the factory method suitable for templated classes?
Kind regards
You need to checkIn("car1", something) into Factory<double> for the obj1 not to be nullptr.
As you commented (please edit that clarification into your question text as well) you expected that car1<double>::checkedIn does that. Unfortunately no, C++ standard says something like that:
Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
As the car1<double>::checkedIn is never used in a way that requires it to exist the compiler is not allowed to initialize it with the side effects that you desire.
And so as the side effects of that initialization may never occur there is nothing checked in and you get nullptr from Factory<double>::create() like required.
Other than that why your code does what it does in so complex manner is quite a mystery for me so I can only describe that it behaves like has been written.
I am in the process of re-working my game engine to use smart-pointers. I have an Object class which everything inherits from. I have a GameObject which is renderable so it inherits from IRenderable (a class that defines a pure virtual render function) and does not inherit from Object. I have a RenderSystem which is supposed to hold a shared_ptr to all IRenderable in the scene.
The problem that I have is how do I cast my GameObject shared_ptr to an IRenderable for the RenderSystem?
Ideas that I have tried:
RenderSystem uses shared_ptr of GameObject but this doesn't work as it is dangerous because not all gameObjects are renderable.
Have IRenderable inherit from Object which should allow for me to inherit from it. This would mean that IRenderable is no longer an interface as Object has other functions included.
This is completely do-able with raw pointers and as such, I feel like there is some way to achieve the same result with smart pointers
Example:
// Object.h
class Object : public enable_shared_from_this<Object> { ... }
// GameObject.h
class GameObject : public Object { ... }
// MeshRenderer.h
class MeshRenderer : public GameObject, IRenderable {
public:
void initialize()
{
// Not able to cast Object to IRenderable
RenderSystem::instance().addRenderable(getShared());
// AND
// Not able to cast Object to IRenderable
RenderSystem::instance().addRenderable(std::static_pointer_cast<IRenderable>(getShared()));
}
}
// RenderSystem.h
class RenderSystem
{
std::list<std::shared_ptr<IRenderable>> m_renderables;
public:
void addRenderable(std::shared_ptr<IRenderable> ptr)
{
m_renderables.push_back(ptr);
}
}
// main.cpp
...
auto meshRenderer = std::shared_ptr<MeshRenderer>();
...
You can't do a static_pointer_cast directly from shared_ptr<Object> to shared_ptr<IRenderable> because those types are unrelated.
But you can cast to the derived type, then allow an implicit conversion to shared_ptr<IRenderable>:
auto p = std::static_pointer_cast<MeshRenderer>(getShared());
std::shared_ptr<IRenderer> q = p;
This performs an explicit conversion from the first base class to the derived type, then an implicit conversion to the second base type. This is statically allowed, because the derived type is known to be related to both bases, but a direct conversion between the unrelated bases isn't possible.
Like this:
#include <memory>
// everything is an Object - yuk, but ok, if you wish...
struct Object : std::enable_shared_from_this<Object>
{
};
struct GameObject : Object
{
};
struct IRenderable
{
virtual void render() {};
};
struct RederableGameObject : GameObject, IRenderable
{
auto as_shared_renderable() -> std::shared_ptr<IRenderable>
{
// builds a new shared pointer to IRenderable which
// uses the same lifetime control block as me
return std::shared_ptr<IRenderable>
{
this->shared_from_this(), // where to get the control block
this // what to point to
};
}
};
Documentation:
See constructor number (8)
http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
Update:
Here is a starting point for a free function to fetch a correct shared_pointer from any object provided it is ultimately publicly derived from std::enable_shared_from_this
#include <memory>
#include <type_traits>
namespace notstd
{
// stuff that I think *should be* std
using namespace std;
// a trait to determine whether class T is derived from template
// Tmpl<...>
template <typename T, template <class...> class Tmpl>
struct is_derived_from_template_impl
{
static std::false_type test(...);
template <typename...Us>
static std::true_type test(Tmpl<Us...> const &);
using result = decltype(test(std::declval<T>()));
};
template <typename T, template <class...> class Tmpl>
using is_derived_from_template = typename is_derived_from_template_impl<T, Tmpl>::result;
template <typename T, template <class...> class Tmpl>
constexpr auto is_derived_from_template_v = is_derived_from_template<T, Tmpl>::value;
// free function version of shared_from_this
template<class T>
auto shared_from(enable_shared_from_this<T>* p)
-> std::shared_ptr<T>
{
return p->shared_from_this();
}
// specific shared_ptr construction from type T
template<class T>
auto shared_from(T*p)
-> enable_if_t
<
is_derived_from_template_v
<
T,
enable_shared_from_this
>,
std::shared_ptr<T>
>
{
return std::shared_ptr<T>(p->shared_from_this(), p);
}
}
// everything is an Object - yuk, but ok, if you wish...
struct Object : std::enable_shared_from_this<Object>
{
};
struct GameObject : Object
{
};
struct IRenderable
{
virtual void render() {};
};
extern int emit(const char* str);
struct RederableGameObject : GameObject, IRenderable
{
auto as_shared_renderable() -> std::shared_ptr<RederableGameObject>
{
return notstd::shared_from(this);
}
auto as_shared_renderable() const -> std::shared_ptr<const RederableGameObject>
{
return notstd::shared_from(this);
}
void e() const {
emit("const");
}
void e() {
emit("mutable");
}
};
int main()
{
auto rgo = std::make_shared<RederableGameObject>();
// prove it works
auto p1 = rgo->as_shared_renderable();
// prove it works with a const object also
auto p2 = static_cast<const RederableGameObject&>(*rgo).as_shared_renderable();
p1->e();
p2->e();
}
I have a file: Base.h
class Base;
class DerivedA : public Base;
class DerivedB : public Base;
/*etc...*/
and another file: 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.*/
Is there a way to somehow convert this string to an actual type (class), so that BaseFactory wouldn't have to know all the possible Derived classes, and have if() for each one of them? Can I produce a class from this string?
I think this can be done in C# through Reflection. Is there something similar in C++?
Nope, there is none, unless you do the mapping yourself. C++ has no mechanism to create objects whose types are determined at runtime. You can use a map to do that mapping yourself, though:
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>;
And then you can do
return map[some_string]();
Getting a new instance. Another idea is to have the types register themself:
// 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");
You could decide to create a macro for the registration
#define REGISTER_DEC_TYPE(NAME) \
static DerivedRegister<NAME> reg
#define REGISTER_DEF_TYPE(NAME) \
DerivedRegister<NAME> NAME::reg(#NAME)
I'm sure there are better names for those two though. Another thing which probably makes sense to use here is shared_ptr.
If you have a set of unrelated types that have no common base-class, you can give the function pointer a return type of boost::variant<A, B, C, D, ...> instead. Like if you have a class Foo, Bar and Baz, it looks like this:
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;
A boost::variant is like an union. It knows which type is stored in it by looking what object was used for initializing or assigning to it. Have a look at its documentation here. Finally, the use of a raw function pointer is also a bit oldish. Modern C++ code should be decoupled from specific functions / types. You may want to look into Boost.Function to look for a better way. It would look like this then (the map):
typedef std::map<std::string, boost::function<variant_type()> > map_type;
std::function will be available in the next version of C++ too, including std::shared_ptr.
No there isn't. My preferred solution to this problem is to create a dictionary which maps name to creation method. Classes that want to be created like this then register a creation method with the dictionary. This is discussed in some detail in the GoF patterns book.
The short answer is you can't. See these SO questions for why:
Why does C++ not have reflection?
How can I add reflection to a C++ application?
I have answered in another SO question about C++ factories. Please see there if a flexible factory is of interest. I try to describe an old way from ET++ to use macros which has worked great for me.
ET++ was a project to port old MacApp to C++ and X11. In the effort of it Eric Gamma etc started to think about Design Patterns
boost::functional has a factory template which is quite flexible: http://www.boost.org/doc/libs/1_54_0/libs/functional/factory/doc/html/index.html
My preference though is to generate wrapper classes which hide the mapping and object creation mechanism. The common scenario I encounter is the need to map different derived classes of some base class to keys, where the derived classes all have a common constructor signature available. Here is the solution I've come up with so far.
#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
I am generally opposed to heavy macro use, but I've made an exception here. The above code generates GENERIC_FACTORY_MAX_ARITY + 1 versions of a class named GenericFactory_N, for each N between 0 and GENERIC_FACTORY_MAX_ARITY inclusive.
Using the generated class templates is easy. Suppose you want a factory to create BaseClass derived objects using a string mapping. Each of the derived objects take 3 integers as constructor parameters.
#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);
The GenericFactory_N class destructor is virtual to allow the following.
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;
Note that this line of the generic factory generator macro
#define BOOST_PP_FILENAME_1 "GenericFactory.hpp"
Assumes the generic factory header file is named GenericFactory.hpp
Detail solution for registering the objects, and accessing them with string names.
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;
}
Compile and Run it (Have done this with Eclipse)
Output:
Base constructor
test1 constructor m_a=10m_b=20
Base constructor
test1 constructor m_a=30m_b=40
Tor Brede Vekterli provides a boost extension that gives exactly the functionality you seek. Currently, it is slightly awkward fitting with current boost libs, but I was able to get it working with 1.48_0 after changing its base namespace.
http://arcticinteractive.com/static/boost/libs/factory/doc/html/factory/factory.html#factory.factory.reference
In answer to those who question why such a thing (as reflection) would be useful for c++ - I use it for interactions between the UI and an engine - the user selects an option in the UI, and the engine takes the UI selection string, and produces an object of the desired type.
The chief benefit of using the framework here (over maintaining a fruit-list somewhere) is that the registering function is in each class's definition (and only requires one line of code calling the registration function per registered class) - as opposed to a file containing the fruit-list, which must be manually added to each time a new class is derived.
I made the factory a static member of my base class.
Meaning reflection as in Java.
there is some info here:
http://msdn.microsoft.com/en-us/library/y0114hz2(VS.80).aspx
Generally speaking, search google for "c++ reflection"
This is the factory pattern. See wikipedia (and this example). You cannot create a type per se from a string without some egregious hack. Why do you need this?
Yes, it is possible, without the use of frameworks and macros, just getting the memory address of the class methods and constructors. You can retrieve them from the map generated by the linker, when configured for this action.
visit this site
https://ealaframework.no-ip.org/wiki/page/c.reference
A C++11-style full example:
// Base.h
class Base;
class DerivedA : public Base;
class DerivedB : public Base;
// BaseFactory.h
class BaseFactory
{
public:
static BaseFactory& get() {
static BaseFactory singleton;
return singleton;
}
virtual ~BaseFactory() {};
BaseFactory(const BaseFactory&) = delete;
BaseFactory(BaseFactory&&) = delete;
template <class DerivedClass>
static std::shared_ptr<Base> creator()
{
return std::shared_ptr<Base>(new DerivedClass());
}
template <class DerivedClass>
void register_class(const std::string& class_name)
{
if (name_to_creator_map.find(class_name) == name_to_creator_map.end())
{
std::function<std::shared_ptr<Base>(void)> functor = &BaseFactory::template creator<DerivedClass>;
name_to_creator_map.emplace(class_name, functor);
}
}
std::shared_ptr<Base> create(const std::string& class_name) const;
private:
BaseFactory();
std::map<std::string, std::function<std::shared_ptr<Base>(void)>> name_to_creator_map;
};
// example.cpp using BaseFactory
BaseFactory::get().register_class<DerivedA>("DerivedA");
BaseFactory::get().register_class<DerivedB>("DerivedB");
auto a_obj = BaseFactory::get().create("DerivedA");
auto b_obj = BaseFactory::get().create("DerivedB");
There is a ready-to-use reflection library https://www.rttr.org/ . You can easily instantiate class by string with it.
struct MyStruct { MyStruct() {}; void func(double) {}; int data; };
RTTR_REGISTRATION
{
registration::class_<MyStruct>("MyStruct")
.constructor<>()
.property("data", &MyStruct::data)
.method("func", &MyStruct::func);
}
type t = type::get_by_name("MyStruct");
variant var = t.create();
I tried to create an SSCE, because this usually also helps to find an issue early on. However, I can't seem to find a solution for this, so I would like to know if it is possible to define an argument which is an unspecified template class pointer.
I have an interface defined, and a parser class, which should handle the implementation details for xerces (like transcoding and all this overhead). The interface class would be designed to create the objects from the (SAX)parser, but without having to deal with the xerces library.
In Java I know I could use an unspecified generic type argument like this:
class Parser
{
public Parser(IGenericInterface<?> oImpl) {};
}
And basically I'm would like to know how this can be done in C++. In the below example I get a compiler error on the line declaring the interface variable because it is missing the type. But of course in the class declaration the type is unknown and should get assigned during runtime as shown in main.
#include <iostream>
#include <string>
template <class T>
class IGenericInterface
{
public:
IGenericInterface() {};
virtual ~IGenericInterface() {};
virtual T *createInstance(void) = 0;
};
template <class T>
class Implementation : public IGenericInterface<T>
{
public:
Implementation() {};
virtual ~Implementation() {};
T *createInstance(void)
{
T * t = new T;
return t;
}
};
class Parser
{
public:
Parser(IGenericInterface *oImpl) { mImpl = oImpl; };
virtual ~Parser() { delete mImpl; };
void doSomething(void) { do whatrever is needed; t = createInstance(); };
private:
IGenericInterface *mImpl;
};
int main()
{
Parser *p = new Parser(new Implementation<int>());
sleep(3);
return 0;
}
So how do I have to define the Parser constructor to make it pass an arbitrary interface argument?
C++ is a static language, so any types must be resolved at compile time. Hence, what you are doing in java cannot be done in the same way in C++. Instead, you use either dynamic polymorphism (using inheritance) or "static polymorphism", using templates (resolved at compile time) with CRTP.
Mixing static and dynamic polymorphism is a no go (exemptions might apply)
template <class T>
class IGenericInterface
{
public:
IGenericInterface() {};
virtual ~IGenericInterface() {};
virtual T *createInstance(void) = 0;
};
And your use of pointers is a nightmare.
Since apparently a generic like in Java can not be implemented in C++, I found a different solution which also allows me to keep the details of the parser separated.
The functions that should have been in the Interface class are now moved to the parser class as virtual abstract functions. The I can define a template which derives from the parser, thus be forced to implement the virtual functions, which basically is what I wanted.
The pattern looks like this now:
template <class T>
class ISerialization
{
public:
virtual ~ISerialization(void) {};
public:
virtual std::string serialize(void) = 0;
virtual bool deserialize(std::vector<T *> &oObjects, std::string const &oSerialized) = 0;
};
class parser
{
void parsing(void) { abstract_function(); }
virtual void abstract_function() = 0;
};
class implementation : public ISerialization<Task>, public parser
{
std::string serialize(void) {};
bool deserialize(std::vector<T *> &oObjects, std::string const &oSerialized) {};
void abstract_function() { specific implementation goes here};
};
Is it possible in C++ to have a member function that is both static and virtual? Apparently, there isn't a straightforward way to do it (static virtual member(); is a compile error), but is there at least a way to achieve the same effect?
I.E:
struct Object
{
struct TypeInformation;
static virtual const TypeInformation &GetTypeInformation() const;
};
struct SomeObject : public Object
{
static virtual const TypeInformation &GetTypeInformation() const;
};
It makes sense to use GetTypeInformation() both on an instance (object->GetTypeInformation()) and on a class (SomeObject::GetTypeInformation()), which can be useful for comparisons and vital for templates.
The only ways I can think of involves writing two functions / a function and a constant, per class, or use macros.
Any other solutions?
No, there's no way to do it, since what would happen when you called Object::GetTypeInformation()? It can't know which derived class version to call since there's no object associated with it.
You'll have to make it a non-static virtual function to work properly; if you also want to be able to call a specific derived class's version non-virtually without an object instance, you'll have to provide a second redunduant static non-virtual version as well.
Many say it is not possible, I would go one step further and say it is not meaningfull.
A static member is something that does not relate to any instance, only to the class.
A virtual member is something that does not relate directly to any class, only to an instance.
So a static virtual member would be something that does not relate to any instance or any class.
I ran into this problem the other day: I had some classes full of static methods but I wanted to use inheritance and virtual methods and reduce code repetition. My solution was:
Instead of using static methods, use a singleton with virtual methods.
In other words, each class should contain a static method that you call to get a pointer to a single, shared instance of the class. You can make the true constructors private or protected so that outside code can't misuse it by creating additional instances.
In practice, using a singleton is a lot like using static methods except that you can take advantage of inheritance and virtual methods.
While Alsk has already given a pretty detailed answer, I'd like to add an alternative, since I think his enhanced implementation is overcomplicated.
We start with an abstract base class, that provides the interface for all the object types:
class Object
{
public:
virtual char* GetClassName() = 0;
};
Now we need an actual implementation. But to avoid having to write both the static and the virtual methods, we will have our actual object classes inherit the virtual methods. This does obviously only work, if the base class knows how to access the static member function. So we need to use a template and pass the actual objects class name to it:
template<class ObjectType>
class ObjectImpl : public Object
{
public:
virtual char* GetClassName()
{
return ObjectType::GetClassNameStatic();
}
};
Finally we need to implement our real object(s). Here we only need to implement the static member function, the virtual member functions will be inherited from the ObjectImpl template class, instantiated with the name of the derived class, so it will access it's static members.
class MyObject : public ObjectImpl<MyObject>
{
public:
static char* GetClassNameStatic()
{
return "MyObject";
}
};
class YourObject : public ObjectImpl<YourObject>
{
public:
static char* GetClassNameStatic()
{
return "YourObject";
}
};
Let's add some code to test:
char* GetObjectClassName(Object* object)
{
return object->GetClassName();
}
int main()
{
MyObject myObject;
YourObject yourObject;
printf("%s\n", MyObject::GetClassNameStatic());
printf("%s\n", myObject.GetClassName());
printf("%s\n", GetObjectClassName(&myObject));
printf("%s\n", YourObject::GetClassNameStatic());
printf("%s\n", yourObject.GetClassName());
printf("%s\n", GetObjectClassName(&yourObject));
return 0;
}
Addendum (Jan 12th 2019):
Instead of using the GetClassNameStatic() function, you can also define the the class name as a static member, even "inline", which IIRC works since C++11 (don't get scared by all the modifiers :)):
class MyObject : public ObjectImpl<MyObject>
{
public:
// Access this from the template class as `ObjectType::s_ClassName`
static inline const char* const s_ClassName = "MyObject";
// ...
};
It is possible!
But what exactly is possible, let's narrow down. People often want some kind of "static virtual function" because of duplication of code needed for being able to call the same function through static call "SomeDerivedClass::myfunction()" and polymorphic call "base_class_pointer->myfunction()". "Legal" method for allowing such functionality is duplication of function definitions:
class Object
{
public:
static string getTypeInformationStatic() { return "base class";}
virtual string getTypeInformation() { return getTypeInformationStatic(); }
};
class Foo: public Object
{
public:
static string getTypeInformationStatic() { return "derived class";}
virtual string getTypeInformation() { return getTypeInformationStatic(); }
};
What if base class has a great number of static functions and derived class has to override every of them and one forgot to provide a duplicating definition for virtual function. Right, we'll get some strange error during runtime which is hard to track down. Cause duplication of code is a bad thing. The following tries to resolve this problem (and I want to tell beforehand that it is completely type-safe and doesn't contain any black magic like typeid's or dynamic_cast's :)
So, we want to provide only one definition of getTypeInformation() per derived class and it is obvious that it has to be a definition of static function because it is not possible to call "SomeDerivedClass::getTypeInformation()" if getTypeInformation() is virtual. How can we call static function of derived class through pointer to base class? It is not possible with vtable because vtable stores pointers only to virtual functions and since we decided not to use virtual functions, we cannot modify vtable for our benefit. Then, to be able to access static function for derived class through pointer to base class we have to store somehow the type of an object within its base class. One approach is to make base class templatized using "curiously recurring template pattern" but it is not appropriate here and we'll use a technique called "type erasure":
class TypeKeeper
{
public:
virtual string getTypeInformation() = 0;
};
template<class T>
class TypeKeeperImpl: public TypeKeeper
{
public:
virtual string getTypeInformation() { return T::getTypeInformationStatic(); }
};
Now we can store the type of an object within base class "Object" with a variable "keeper":
class Object
{
public:
Object(){}
boost::scoped_ptr<TypeKeeper> keeper;
//not virtual
string getTypeInformation() const
{ return keeper? keeper->getTypeInformation(): string("base class"); }
};
In a derived class keeper must be initialized during construction:
class Foo: public Object
{
public:
Foo() { keeper.reset(new TypeKeeperImpl<Foo>()); }
//note the name of the function
static string getTypeInformationStatic()
{ return "class for proving static virtual functions concept"; }
};
Let's add syntactic sugar:
template<class T>
void override_static_functions(T* t)
{ t->keeper.reset(new TypeKeeperImpl<T>()); }
#define OVERRIDE_STATIC_FUNCTIONS override_static_functions(this)
Now declarations of descendants look like:
class Foo: public Object
{
public:
Foo() { OVERRIDE_STATIC_FUNCTIONS; }
static string getTypeInformationStatic()
{ return "class for proving static virtual functions concept"; }
};
class Bar: public Foo
{
public:
Bar() { OVERRIDE_STATIC_FUNCTIONS; }
static string getTypeInformationStatic()
{ return "another class for the same reason"; }
};
usage:
Object* obj = new Foo();
cout << obj->getTypeInformation() << endl; //calls Foo::getTypeInformationStatic()
obj = new Bar();
cout << obj->getTypeInformation() << endl; //calls Bar::getTypeInformationStatic()
Foo* foo = new Bar();
cout << foo->getTypeInformation() << endl; //calls Bar::getTypeInformationStatic()
Foo::getTypeInformation(); //compile-time error
Foo::getTypeInformationStatic(); //calls Foo::getTypeInformationStatic()
Bar::getTypeInformationStatic(); //calls Bar::getTypeInformationStatic()
Advantages:
less duplication of code (but we
have to call
OVERRIDE_STATIC_FUNCTIONS in every
constructor)
Disadvantages:
OVERRIDE_STATIC_FUNCTIONS in every
constructor
memory and performance
overhead
increased complexity
Open issues:
1) there are different names for static and virtual functions
how to solve ambiguity here?
class Foo
{
public:
static void f(bool f=true) { cout << "static";}
virtual void f() { cout << "virtual";}
};
//somewhere
Foo::f(); //calls static f(), no ambiguity
ptr_to_foo->f(); //ambiguity
2) how to implicitly call OVERRIDE_STATIC_FUNCTIONS inside every constructor?
It is possible. Make two functions: static and virtual
struct Object{
struct TypeInformation;
static const TypeInformation &GetTypeInformationStatic() const
{
return GetTypeInformationMain1();
}
virtual const TypeInformation &GetTypeInformation() const
{
return GetTypeInformationMain1();
}
protected:
static const TypeInformation &GetTypeInformationMain1(); // Main function
};
struct SomeObject : public Object {
static const TypeInformation &GetTypeInformationStatic() const
{
return GetTypeInformationMain2();
}
virtual const TypeInformation &GetTypeInformation() const
{
return GetTypeInformationMain2();
}
protected:
static const TypeInformation &GetTypeInformationMain2(); // Main function
};
No, this is not possible, because static member functions lack a this pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.
virtual functions in a class needs the this pointer, and is very coupled to the class, hence they can't be static.
It's not possible, but that's just because an omission. It isn't something that "doesn't make sense" as a lot of people seem to claim. To be clear, I'm talking about something like this:
struct Base {
static virtual void sayMyName() {
cout << "Base\n";
}
};
struct Derived : public Base {
static void sayMyName() override {
cout << "Derived\n";
}
};
void foo(Base *b) {
b->sayMyName();
Derived::sayMyName(); // Also would work.
}
This is 100% something that could be implemented (it just hasn't), and I'd argue something that is useful.
Consider how normal virtual functions work. Remove the statics and add in some other stuff and we have:
struct Base {
virtual void sayMyName() {
cout << "Base\n";
}
virtual void foo() {
}
int somedata;
};
struct Derived : public Base {
void sayMyName() override {
cout << "Derived\n";
}
};
void foo(Base *b) {
b->sayMyName();
}
This works fine and basically what happens is the compiler makes two tables, called VTables, and assigns indices to the virtual functions like this
enum Base_Virtual_Functions {
sayMyName = 0;
foo = 1;
};
using VTable = void*[];
const VTable Base_VTable = {
&Base::sayMyName,
&Base::foo
};
const VTable Derived_VTable = {
&Derived::sayMyName,
&Base::foo
};
Next each class with virtual functions is augmented with another field that points to its VTable, so the compiler basically changes them to be like this:
struct Base {
VTable* vtable;
virtual void sayMyName() {
cout << "Base\n";
}
virtual void foo() {
}
int somedata;
};
struct Derived : public Base {
VTable* vtable;
void sayMyName() override {
cout << "Derived\n";
}
};
Then what actually happens when you call b->sayMyName()? Basically this:
b->vtable[Base_Virtual_Functions::sayMyName](b);
(The first parameter becomes this.)
Ok fine, so how would it work with static virtual functions? Well what's the difference between static and non-static member functions? The only difference is that the latter get a this pointer.
We can do exactly the same with static virtual functions - just remove the this pointer.
b->vtable[Base_Virtual_Functions::sayMyName]();
This could then support both syntaxes:
b->sayMyName(); // Prints "Base" or "Derived"...
Base::sayMyName(); // Always prints "Base".
So ignore all the naysayers. It does make sense. Why isn't it supported then? I think it's because it has very little benefit and could even be a little confusing.
The only technical advantage over a normal virtual function is that you don't need to pass this to the function but I don't think that would make any measurable difference to performance.
It does mean you don't have a separate static and non-static function for cases when you have an instance, and when you don't have an instance, but also it might be confusing that it's only really "virtual" when you use the instance call.
Well , quite a late answer but it is possible using the curiously recurring template pattern. This wikipedia article has the info you need and also the example under static polymorphism is what you are asked for.
This question is over a decade old, but it looks like it gets a good amount of traffic, so I wanted to post an alternative using modern C++ features that I haven't seen anywhere else.
This solution uses CRTP and SFINAE to perform static dispatching. That, in itself, is nothing new, but all such implementations I've found lack strict signature checking for "overrides." This implementation requires that the "overriding" method signature exactly matches that of the "overridden" method. This behavior more closely resembles that of virtual functions, while also allowing us to effectively overload and "override" a static method.
Note that I put override in quotes because, strictly speaking, we're not technically overriding anything. Instead, we're calling a dispatch method X with signature Y that forwards all of its arguments to T::X, where T is to the first type among a list of types such that T::X exists with signature Y. This list of types considered for dispatching can be anything, but generally would include a default implementation class and the derived class.
Implementation
#include <experimental/type_traits>
template <template <class...> class Op, class... Types>
struct dispatcher;
template <template <class...> class Op, class T>
struct dispatcher<Op, T> : std::experimental::detected_t<Op, T> {};
template <template <class...> class Op, class T, class... Types>
struct dispatcher<Op, T, Types...>
: std::experimental::detected_or_t<
typename dispatcher<Op, Types...>::type, Op, T> {};
// Helper to convert a signature to a function pointer
template <class Signature> struct function_ptr;
template <class R, class... Args> struct function_ptr<R(Args...)> {
using type = R (*)(Args...);
};
// Macro to simplify creation of the dispatcher
// NOTE: This macro isn't smart enough to handle creating an overloaded
// dispatcher because both dispatchers will try to use the same
// integral_constant type alias name. If you want to overload, do it
// manually or make a smarter macro that can somehow put the signature in
// the integral_constant type alias name.
#define virtual_static_method(name, signature, ...) \
template <class VSM_T> \
using vsm_##name##_type = std::integral_constant< \
function_ptr<signature>::type, &VSM_T::name>; \
\
template <class... VSM_Args> \
static auto name(VSM_Args&&... args) \
{ \
return dispatcher<vsm_##name##_type, __VA_ARGS__>::value( \
std::forward<VSM_Args>(args)...); \
}
Example Usage
#include <iostream>
template <class T>
struct Base {
// Define the default implementations
struct defaults {
static std::string alpha() { return "Base::alpha"; };
static std::string bravo(int) { return "Base::bravo"; }
};
// Create the dispatchers
virtual_static_method(alpha, std::string(void), T, defaults);
virtual_static_method(bravo, std::string(int), T, defaults);
static void where_are_the_turtles() {
std::cout << alpha() << std::endl; // Derived::alpha
std::cout << bravo(1) << std::endl; // Base::bravo
}
};
struct Derived : Base<Derived> {
// Overrides Base::alpha
static std::string alpha(){ return "Derived::alpha"; }
// Does not override Base::bravo because signatures differ (even though
// int is implicitly convertible to bool)
static std::string bravo(bool){ return "Derived::bravo"; }
};
int main() {
Derived::where_are_the_turtles();
}
I think what you're trying to do can be done through templates. I'm trying to read between the lines here. What you're trying to do is to call a method from some code, where it calls a derived version but the caller doesn't specify which class. Example:
class Foo {
public:
void M() {...}
};
class Bar : public Foo {
public:
void M() {...}
};
void Try()
{
xxx::M();
}
int main()
{
Try();
}
You want Try() to call the Bar version of M without specifying Bar. The way you do that for statics is to use a template. So change it like so:
class Foo {
public:
void M() {...}
};
class Bar : public Foo {
public:
void M() {...}
};
template <class T>
void Try()
{
T::M();
}
int main()
{
Try<Bar>();
}
No, Static member function can't be virtual .since virtual concept is resolved at run time with the help of vptr, and vptr is non static member of a class.due to that static member function can't acess vptr so static member can't be virtual.
No, its not possible, since static members are bound at compile time, while virtual members are bound at runtime.
If your desired use for a virtual static is to be able to define an interface over the static section of a class then there is a solution to your problem using C++20 concept's.
class ExBase { //object properties
public: virtual int do(int) = 0;
};
template <typename T> //type properties
concept ExReq = std::derived_from<T, ExBase> && requires(int i) { //~constexpr bool
{
T::do_static(i) //checks that this compiles
} -> std::same_as<int> //checks the expression type is int
};
class ExImpl : virtual public ExBase { //satisfies ExReq
public: int do(int i) override {return i;} //overrides do in ExBase
public: static int do_static(int i) {return i;} //satisfies ExReq
};
//...
void some_func(ExReq auto o) {o.do(0); decltype(o)::do_static(0);}
(this works the same way on members aswell!)
For more on how concepts work: https://en.cppreference.com/w/cpp/language/constraints
For the standard concepts added in C++20: https://en.cppreference.com/w/cpp/concepts
First, the replies are correct that what the OP is requesting is a contradiction in terms: virtual methods depend on the run-time type of an instance; static functions specifically don't depend on an instance -- just on a type. That said, it makes sense to have static functions return something specific to a type. For example, I had a family of MouseTool classes for the State pattern and I started having each one have a static function returning the keyboard modifier that went with it; I used those static functions in the factory function that made the correct MouseTool instance. That function checked the mouse state against MouseToolA::keyboardModifier(), MouseToolB::keyboardModifier(), etc. and then instantiated the appropriate one. Of course later I wanted to check if the state was right so I wanted write something like "if (keyboardModifier == dynamic_type(*state)::keyboardModifier())" (not real C++ syntax), which is what this question is asking.
So, if you find yourself wanting this, you may want to rething your solution. Still, I understand the desire to have static methods and then call them dynamically based on the dynamic type of an instance. I think the Visitor Pattern can give you what you want. It gives you what you want. It's a bit of extra code, but it could be useful for other visitors.
See: http://en.wikipedia.org/wiki/Visitor_pattern for background.
struct ObjectVisitor;
struct Object
{
struct TypeInformation;
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v);
};
struct SomeObject : public Object
{
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v) const;
};
struct AnotherObject : public Object
{
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v) const;
};
Then for each concrete Object:
void SomeObject::accept(ObjectVisitor& v) const {
v.visit(*this); // The compiler statically picks the visit method based on *this being a const SomeObject&.
}
void AnotherObject::accept(ObjectVisitor& v) const {
v.visit(*this); // Here *this is a const AnotherObject& at compile time.
}
and then define the base visitor:
struct ObjectVisitor {
virtual ~ObjectVisitor() {}
virtual void visit(const SomeObject& o) {} // Or = 0, depending what you feel like.
virtual void visit(const AnotherObject& o) {} // Or = 0, depending what you feel like.
// More virtual void visit() methods for each Object class.
};
Then the concrete visitor that selects the appropriate static function:
struct ObjectVisitorGetTypeInfo {
Object::TypeInformation result;
virtual void visit(const SomeObject& o) {
result = SomeObject::GetTypeInformation();
}
virtual void visit(const AnotherObject& o) {
result = AnotherObject::GetTypeInformation();
}
// Again, an implementation for each concrete Object.
};
finally, use it:
void printInfo(Object& o) {
ObjectVisitorGetTypeInfo getTypeInfo;
Object::TypeInformation info = o.accept(getTypeInfo).result;
std::cout << info << std::endl;
}
Notes:
Constness left as an exercise.
You returned a reference from a static. Unless you have a singleton, that's questionable.
If you want to avoid copy-paste errors where one of your visit methods calls the wrong static function, you could use a templated helper function (which can't itself be virtual) t your visitor with a template like this:
struct ObjectVisitorGetTypeInfo {
Object::TypeInformation result;
virtual void visit(const SomeObject& o) { doVisit(o); }
virtual void visit(const AnotherObject& o) { doVisit(o); }
// Again, an implementation for each concrete Object.
private:
template <typename T>
void doVisit(const T& o) {
result = T::GetTypeInformation();
}
};
With c++ you can use static inheritance with the crt method. For the example, it is used widely on window template atl & wtl.
See https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
To be simple, you have a class that is templated from itself like class myclass : public myancestor. From this point the myancestor class can now call your static T::YourImpl function.
I had a browse through the other answers and none of them seem to mention virtual function tables (vtable), which explains why this is not possible.
A static function inside a C++ class compiles to something which is effectively the same as any other function in a regular namespace.
In other words, when you declare a function static you are using the class name as a namespace rather than an object (which has an instance, with some associated data).
Let's quickly look at this...
// This example is the same as the example below
class ExampleClass
{
static void exampleFunction();
int someData;
};
// This example is the same as the example above
namespace ExampleClass
{
void exampleFunction();
// Doesn't work quite the same. Each instance of a class
// has independent data. Here the data is global.
int someData;
}
With that out of the way, and an understanding of what a static member function really is, we can now consider vtables.
If you declare any virtual function in a class, then the compiler creates a block of data which (usually) precedes other data members. This block of data contains runtime information which tells the program at runtime where in memory it needs to jump to in order to execute the correct (virtual) function for each instance of a class which might be created during runtime.
The important point here is "block of data". In order for that block of data to exist, it has to be stored as part of an instance of an object (class). If your function is static, then we already said it uses the name of the class as a namespace. There is no object associated with that function call.
To add slightly more detail: A static function does not have an implicit this pointer, which points to the memory where the object lives. Because it doesn't have that, you can't jump to a place in memory and find the vtable for that object. So you can't do virtual function dispatch.
I'm not an expert in compiler engineering by any means, but understanding things at least to this level of detail is helpful, and (hopefully?) makes it easy to understand why (at least in C++) static virtual does not make sense, and cannot be translated into something sensible by the compiler.
Maybe you can try my solution below:
class Base {
public:
Base(void);
virtual ~Base(void);
public:
virtual void MyVirtualFun(void) = 0;
static void MyStaticFun(void) { assert( mSelf != NULL); mSelf->MyVirtualFun(); }
private:
static Base* mSelf;
};
Base::mSelf = NULL;
Base::Base(void) {
mSelf = this;
}
Base::~Base(void) {
// please never delete mSelf or reset the Value of mSelf in any deconstructors
}
class DerivedClass : public Base {
public:
DerivedClass(void) : Base() {}
~DerivedClass(void){}
public:
virtual void MyVirtualFun(void) { cout<<"Hello, it is DerivedClass!"<<endl; }
};
int main() {
DerivedClass testCls;
testCls.MyStaticFun(); //correct way to invoke this kind of static fun
DerivedClass::MyStaticFun(); //wrong way
return 0;
}
Like others have said, there are 2 important pieces of information:
there is no this pointer when making a static function call and
the this pointer points to the structure where the virtual table, or thunk, are used to look up which runtime method to call.
A static function is determined at compile time.
I showed this code example in C++ static members in class; it shows that you can call a static method given a null pointer:
struct Foo
{
static int boo() { return 2; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo* pFoo = NULL;
int b = pFoo->boo(); // b will now have the value 2
return 0;
}