What does my slot class miss that std::function has? - c++

I wrote my own "slot" aka "callable wrapper" because I wanted to provide member function slot rebinding on other objects (i.e. I needed a way to store the member function pointer and a pointer to the class in question).
I ran a small size test and discovered std::function on my system (64-bit Linux) was twice (GCC/libstdc++) to three times (Clang/libc++) the size of my own implementation of a similar class, with a size of 16 bytes. The implementation for non-member functions and lambda's goes like this (the const void* first argument is for uniformity with member function slots not shown here):
template<typename... ArgTypes>
class slot
{
public:
virtual ~slot() = default;
virtual void operator()(const void* object, ArgTypes...) const = 0;
protected:
slot() = default;
};
template<typename Callable, typename... ArgTypes>
class callable_slot : public slot<ArgTypes...>
{
public:
callable_slot(Callable function_pointer_or_lambda) : callable(function_pointer_or_lambda) {}
virtual void operator()(const void*, ArgTypes... args) const override { callable(args...); }
private:
Callable callable;
};
template<typename Callable>
class callable_slot<Callable> : public slot<>
{
public:
callable_slot(Callable function_pointer_or_lambda) : callable(function_pointer_or_lambda) {}
virtual void operator()(const void*) const override { callable(); }
private:
Callable callable;
};
template<typename Callable, typename... ArgTypes>
using function_slot = callable_slot<Callable, ArgTypes...>;
I understand things like target aren't implemented here, but I don't think any of the missing functions increase the size of the object.
What I'm asking is: why is std::function larger in size than my cheap implementation above?

Your function_slot takes a Callable and set of args..., and returns a type inheriting from slot<args...> with a virtual operator().
To use it polymorphically as a value, you'd have to wrap it in a smart pointer and store it on the heap, and you'd have to forward the wrapping classes operator() to the slot<args...> one.
std::function corresponds to that wrapper, not to your slot or callable_slot object.
template<class...Args>
struct smart_slot {
template<class Callable> // add SFINAE tests here TODO! IMPORTANT!
smart_slot( Callable other ):
my_slot( std::make_unique<callable_slot<Callable, Args...>>( std::move(other) ) )
{}
void operator()( Args...args ) const {
return (*my_slot)(std::forward<Args>(args)...);
}
// etc
private:
std::unique_ptr<slot<Args...>> my_slot;
};
smart_slot is closer to std::function than your code. As far as std::function is concerned, everything you wrote is an implementation detail that users of std::function wouldn't ever see.
Now, this would only require that std::function be the size of one pointer. std::function is larger because it has what is known as small object optimization.
Instead of just storing a smart pointer, it has a block of memory within itself. If the object you pass in fits in that block of memory, it constructs it in-place that block of memory instead of doing a heap allocation.
std::function is basically mandated to do this for simple cases like being passed a function pointer. Quality implementations do it for larger and more complex objects. MSVC does it for objects up to the size of two std::strings.
This means if you do this:
std::function<void(std::ostream&)> hello_world =
[s = "hello world"s](std::ostream& os)
{
os << s;
};
hello_world(std::cout);
it does no dynamic allocation on a decent implementation of std::function.
Note that some major library vendors do dynamic allocation in this case.

Your class functionality is very different from the one provided by std::function. You request users of your class to provide the actual type of 'callable' object as an argument of the template.
On the contrary, std::function does not require this, and can deal with any callable object, as long as it has operator() with required interface. Try using your template with an object of unknown type, for example, a result of std::bind, and you will know what I mean.
Since the functionality is very different, comparison of sizes is moot.

Related

std::any without RTTI, how does it work?

If I want to use std::any I can use it with RTTI switched off. The following example compiles and runs as expected also with -fno-rtti with gcc.
int main()
{
std::any x;
x=9.9;
std::cout << std::any_cast<double>(x) << std::endl;
}
But how std::any stores the type information? As I see, if I call std::any_cast with the "wrong" type I got std::bad_any_cast exception as expected.
How is that realized or is this maybe only a gcc feature?
I found that boost::any did also not need RTTI, but I found also not how that is solved. Does boost::any need RTTI?.
Digging into the STL header itself gives me no answer. That code is nearly unreadable to me.
TL;DR; std::any holds a pointer to a static member function of a templated class. This function can perform many operations and is specific to a given type since the actual instance of the function depends on the template arguments of the class.
The implementation of std::any in libstdc++ is not that complex, you can have a look at it:
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/any
Basically, std::any holds two things:
A pointer to a (dynamically) allocated storage;
A pointer to a "storage manager function":
void (*_M_manager)(_Op, const any*, _Arg*);
When you construct or assign a new std::any with an object of type T, _M_manager points to a function specific to the type T (which is actually a static member function of class specific to T):
template <typename _ValueType,
typename _Tp = _Decay<_ValueType>,
typename _Mgr = _Manager<_Tp>, // <-- Class specific to T.
__any_constructible_t<_Tp, _ValueType&&> = true,
enable_if_t<!__is_in_place_type<_Tp>::value, bool> = true>
any(_ValueType&& __value)
: _M_manager(&_Mgr::_S_manage) { /* ... */ }
Since this function is specific to a given type, you don't need RTTI to perform the operations required by std::any.
Furthermore, it is easy to check that you are casting to the right type within std::any_cast. Here is the core of the gcc implementation of std::any_cast:
template<typename _Tp>
void* __any_caster(const any* __any) {
if constexpr (is_copy_constructible_v<decay_t<_Tp>>) {
if (__any->_M_manager == &any::_Manager<decay_t<_Tp>>::_S_manage) {
any::_Arg __arg;
__any->_M_manager(any::_Op_access, __any, &__arg);
return __arg._M_obj;
}
}
return nullptr;
}
You can see that it is simply an equality check between the stored function inside the object you are trying to cast (_any->_M_manager) and the manager function of the type you want to cast to (&any::_Manager<decay_t<_Tp>>::_S_manage).
The class _Manager<_Tp> is actually an alias to either _Manager_internal<_Tp> or _Manager_external<_Tp> depending on _Tp.
This class is also used for allocation / construction of object for the std::any class.
Manual implementation of a limited RTTI is not that hard. You're gonna need static generic functions. That much I can say without providing a complete implementation.
here is one possibility:
class meta{
static auto id(){
static std::atomic<std::size_t> nextid{};
return ++nextid;//globally unique
};
std::size_t mid=0;//per instance type id
public:
template<typename T>
meta(T&&){
static const std::size_t tid{id()};//classwide unique
mid=tid;
};
meta(meta const&)=default;
meta(meta&&)=default;
meta():mid{}{};
template<typename T>
auto is_a(T&& obj){return mid==meta{obj}.mid;};
};
This is my first observation; far from ideal, missing many details. One may use one instance of meta as a none-static data member of his supposed implementation of std::any.
One of possible solutions is generating unique id for every type possibly stored in any (I assume You know moreless how any internally works). The code that can do it may look something like this:
struct id_gen{
static int &i(){
static int i = 0;
return i;
}
template<class T>
struct gen{
static int id() {
static int id = i()++;
return id;
}
};
};
With this implemented You can use the id of the type instead of RTTI typeinfo to quickly check the type.
Notice the usage of static variables inside functions and static functions. This is done to avoid the problem of undefined order of static variable initialization.

Get base class target from std::function

If I store a polymorphic functor in an std::function, is there a way to extract the functor without knowing the concrete type?
Here is a simplified version of the code:
struct Base {
//...
virtual int operator()(int foo) const = 0;
void setBar(int bar){}
};
struct Derived : Base {
//...
int operator()(int foo) const override {}
};
std::function<int(int)> getFunction() {
return Derived();
}
int main() {
auto f = getFunction();
// How do I call setBar() ?
if (Base* b = f.target<Base>()) {} // Fails: returns nullptr
else if(Derived* d = f.target<Derived>()) {
d->setBar(5); // Works but requires Derived type
}
std::cout << f(7) << std::endl;
return 0;
}
I want the client to be able to provide their own function, and for my handler to use the functionality of the Base if it's available.
The fall back would be of course to just use the abstract base class instead of std::function and clients would implement the ABC interface as they would have pre-C++11:
std::shared_ptr<Base> getFunction {
return std::make_shared<Derived>();
}
but I wanted to know if it's possible to create a more flexible and easier to use interface with C++14. It seems all that's missing is a cast inside std::function::target
It seems all that's missing is a cast inside std::function::target
All target<T> currently needs is to check target_id<T> == stored_type_info.
Being able to cast back to the real (erased) type in a context where that type may not be visible, and then check how it's related to the requested type ... is not really feasible.
Anyway, std::function is polymorphic only on the function signature. That's the thing it abstracts. If you want general-purpose polymorphism, just return a unique_ptr<Base> and use that.
If you really want function<int(int)> for the function-call syntax, instantiate it with a pimpl wrapper for unique_ptr<Base>.
Possible solution would be to have a thin wrapper:
struct BaseCaller {
BaseCaller( std::unique_ptr<Base> ptr ) : ptr_( std::move( ptr ) ) {}
int operator()( int foo ) { return (*ptr)( foo ); }
std::unique_ptr<Base> ptr_;
};
now user must create all derived from Base classed through this wrapper:
std::function<int(int)> getFunction() {
return BaseCaller( std::make_unique<Derived>() );
}
and you check in your call that target is a BaseCaller.
I want the client to be able to provide their own function, and for my handler to use the functionality of the Base if it's available.
The main drawback to using virtual dispatch is that it may create an optimization barrier. For instance, the virtual function calls cannot usually be inlined, and "devirtualization" optimizations are generally pretty difficult for the compiler to actually do in practical situations.
If you are in a situation where the code is performance critical, you can roll your own type-erasure and avoid any vtable / dynamic allocations.
I'm going to follow a pattern demonstrated in an old (but well-known) article, the "Impossibly Fast Delegates".
// Represents a pointer to a class implementing your interface
class InterfacePtr {
using ObjectPtr = void*;
using CallOperator_t = int(*)(ObjectPtr, int);
using SetBar_t = void(ObjectPtr, int);
ObjectPtr obj_;
CallOperator_t call_;
SetBar_t set_bar_;
// Ctor takes any type that implements your interface,
// stores pointer to it as void * and lambda functions
// that undo the cast and forward the call
template <typename T>
InterfacePtr(T * t)
: obj_(static_cast<ObjectPtr>(t))
, call_(+[](ObjectPtr ptr, int i) { return (*static_cast<T*>(ptr))(i); })
, set_bar_(+[](ObjectPtr ptr, int i) { static_cast<T*>(ptr)->set_bar(i); })
{}
int operator()(int i) {
return call_(obj_, i);
}
void set_bar()(int i) {
return set_bar_(obj_, i);
}
};
Then, you would take InterfacePtr instead of a pointer to Base in your API.
If you want the interface member set_bar to be optional, then you could use SFINAE to detect whether set_bar is present, and have two versions of the constructor, one for when it is, and one for when it isn't. There is recently a really great exposition of the "detection idiom" at various C++ standards on Tartan Llama's blog, here. The advantage of that would be that you get something similar to what virtual gives you, with the possibility to optionally override functions, but the dispatch decisions get made at compile-time, and you aren't forced to have a vtable. And all of the functions can potentially be inlined if the optimizer can prove to itself that e.g. in some compilation unit using this, only one type is actually passed to your API through this mechanism.
A difference is that this InterfacePtr is non-owning and doesn't have the dtor or own the storage of the object it's pointing to.
If you want InterfacePtr to be owning, like std::function, and copy the functor into its own memory and take care of deleting it when it goes out of scope, then I'd recommend to use std::any to represent the object instead of void *, and use std::any_cast in the lambdas instead of static_cast<T*> in my implementation. There's some good further discussion of std::any and why it's good for this usecase on /r/cpp here.
I don't think there's any way to do what you were originally asking, and recover the "original" functor type from std::function. Type erasure erases the type, you can't get it back without doing something squirrelly.
Edit: Another alternative you might consider is to use a type-erasure library like dyno
std::function<X>::target<T> can only cast back to exactly T*.
This is because storing how to convert to every type that can be converted to T* would require storing more information. It takes information to convert a pointer-to-derived to a pointer-to-base in the general case in C++.
target is intended to simply permit replacing some function-pointer style machinery with std::functions and have the existing machinery work, and do so with nearly zero cost (just compare typeids). Extending that cost to every base type of the stored type would have been hard, so it wasn't done, and won't be free, so it probably won't be done in the future.
std::function is, however, just an example of type erasure, and you can roll your own with additional functionality.
The first thing I'd do is I would do away with your virtual operator(). Type-erasure based polymorphism doesn't need that.
The second thing is get your hands on an any -- either boost::any or c++17's std::any.
That writes the hard part of type erasure -- small buffer optimization and value storage -- for you.
Add to that your own dispatch table.
template<class Sig>
struct my_extended_function;
template<class R, class...Args>
struct my_extended_function<R(Args...)> {
struct vtable {
R(*f)(any&, Args&&...) = 0;
void*(*cast)(any&, std::type_info const&) = 0;
};
template<class...Bases, class T>
my_extended_function make_with_bases( T t ) {
return {
get_vtable<T, Bases...>(),
std::move(t)
};
}
R operator()(Args...args)const {
return (*p_vtable->f)(state, std::forward<Args>(args)...);
}
private:
template<class T, class...Bases>
static vtable make_vtable() {
vtable ret{
// TODO: R=void needs different version
+[](any& ptr, Args&&...args)->R {
return (*any_cast<T*>(ptr))(std::forward<Args>(args)...);
},
+[](any& ptr, std::type_info const& tid)->void* {
T* pt = any_cast<T*>(ptr);
if (typeid(pt)==tid) return pt;
// TODO: iterate over Bases, see if any match tid
// implicitly cast pt to the Bases* in question, and return it.
}
};
}
template<class T, class...Bases>
vtable const* get_vtable() {
static vtable const r = make_vtable<T,Bases...>();
return &r;
}
vtable const* p_vtable = nullptr;
mutable std::any state;
my_extended_function( vtable const* vt, std::any s ):
p_vtable(vt),
state(std::move(s))
{}
};

How to store type information, gathered from a constructor, at the class level to use in casting

I am trying to write a class that I can store and use type information in without the need for a template parameter.
I want to write something like this:
class Example
{
public:
template<typename T>
Example(T* ptr)
: ptr(ptr)
{
// typedef T EnclosedType; I want this be a avaialable at the class level.
}
void operator()()
{
if(ptr == NULL)
return;
(*(EnclosedType*)ptr)(); // so i can cast the pointer and call the () operator if the class has one.
}
private:
void* ptr;
}
I am not asking how to write an is_functor() class.
I want to know how to get type information in a constructor and store it at the class level. If that is impossible, a different solution to this would be appreciated.
I consider this as a good and valid question, however, there is no general solution beside using a template parameter at the class level. What you tried to achieve in your question -- using a typedef inside a function and then access this in the whole class -- is not possible.
Type erasure
Only if you impose certain restrictions onto your constructor parameters, there are some alternatives. In this respect, here is an example of type erasure where the operator() of some given object is stored inside a std::function<void()> variable.
struct A
{
template<typename T>
A(T const& t) : f (std::bind(&T::operator(), t)) {}
void operator()() const
{
f();
}
std::function<void()> f;
};
struct B
{
void operator()() const
{
std::cout<<"hello"<<std::endl;
}
};
int main()
{
A(B{}).operator()(); //prints "hello"
}
DEMO
Note, however, the assumptions underlying this approach: one assumes that all passed objects have an operator of a given signature (here void operator()) which is stored inside a std::function<void()> (with respect to storing the member-function, see here).
Inheritance
In a sense, type erasure is thus like "inheriting without a base class" -- one could instead use a common base class for all constructor parameter classes with a virtual bracket operator, and then pass a base class pointer to your constructor.
struct A_parameter_base
{
void operator()() const = 0;
};
struct B : public A_parameter_base
{
void operator()() const { std::cout<<"hello"<<std::endl; }
};
struct A
{
A(std::shared_ptr<A_parameter_base> _p) : p(_p) {}
void operator()()
{
p->operator();
}
std::shared_ptr<A_parameter_base> p;
}
That is similar to the code in your question, only that it does not use a void-pointer but a pointer to a specific base class.
Both approaches, type erasure and inheritance, are similar in their applications, but type erasure might be more convenient as one gets rid of a common base class. However, the inheritance approach has the further advantage that you can restore the original object via multiple dispatch
This also shows the limitations of both approaches. If your operator would not be void but instead would return some unknown varying type, you cannot use the above approach but have to use templates. The inheritance parallel is: you cannot have a virtual function template.
The practical answer is to store either a copy of your class, or a std::ref wrapped pseudo-reference to your class, in a std::function<void()>.
std::function type erases things it stores down to 3 concepts: copy, destroy and invoke with a fixed signature. (also, cast-back-to-original-type and typeid, more obscurely)
What it does is it remembers, at construction, how to do these operations to the passed in type, and stores a copy in a way it can perform those operations on it, then forgets everything else about the type.
You cannot remember everything about a type this way. But almost any operation with a fixed signature, or which can be intermediaried via a fixed signature operation, can be type erased down to.
The first typical way to do this are to create a private pure interface with those operations, then create a template implementation (templated on the type passed to the ctor) that implements each operation for that particular type. The class that does the type erasure then stores a (smart) pointer to the private interface, and forwards its public operations to it.
A second typical way is to store a void*, or a buffer of char, and a set of pointers to functions that implement the operations. The pointers to functions can be either stored locally in the type erasing class, or stored in a helper struct that is created statically for each type erased, and a pointer to the helper struct is stored in the type erasing class. The first way to store the function pointers is like C-style object properties: the second is like a manual vtable.
In any case, the function pointers usually take one (or more) void* and know how to cast them back to the right type. They are created in the ctor that knows the type, either as instances of a template function, or as local stateless lambdas, or the same indirectly.
You could even do a hybrid of the two: static pimpl instance pointers taking a void* or whatever.
Often using std::function is enough, manually writing type erasure is hard to get right compared to using std::function.
Another version to the first two answers we have here - that's closer to your current code:
class A{
public:
virtual void operator()=0;
};
template<class T>
class B: public A{
public:
B(T*t):ptr(t){}
virtual void operator(){(*ptr)();}
T*ptr;
};
class Example
{
public:
template<typename T>
Example(T* ptr)
: a(new B<T>(ptr))
{
// typedef T EnclosedType; I want this be a avaialable at the class level.
}
void operator()()
{
if(!a)
return;
(*a)();
}
private:
std::unique_ptr<A> a;
}

how to declare the type of the result of std::make_tuple, without using auto

I want to implement a "Task" class, which can store a function pointer along with some arguments to pass to it. like std::bind(). and I have some question about how to store the arguments.
class BaseTask {
public:
virtual ~BaseTask() {}
virtual void run() = 0;
};
template<typename ... MTArg>
class Task : public BaseTask {
public:
typedef void (*RawFunction)(MTArg...);
Task(RawFunction rawFunction, MTArg&& ... args) : // Q1: MTArg&& ... args
rawFunction(rawFunction),
args(std::make_tuple(std::forward<MTArg>(args)...)) {} // Q2: std::make_tuple(std::forward<MTArg>(args)...)
virtual void run() {
callFunction(GenIndexSequence<sizeof...(MTArg)>()); // struct GenIndexSequence<count> : IndexSequence<0, ..., count-1>
}
private:
template<unsigned int... argIndexs>
inline void callFunction() {
rawFunction(std::forward<MTArg>(std::get<argIndexs>(args))...);
}
private:
RawFunction rawFunction;
std::tuple<MTArg...> args; // Q3: std::tuple<MTArg...>
};
Q1: is && after MTArg necessary
Q2: is this way correct to init args
Q3: is type of args correct, do I need:
std::tuple<special_decay_t<MTArg>...>
according to this: http://en.cppreference.com/w/cpp/utility/tuple/make_tuple
// end of questions
I want Task can be used in this way:
void fun(int i, const int& j) {}
BaseTask* createTask1() {
return new Task<int, const int&>(&fun, 1, 2); // "2" must not be disposed at the time of task.run(), so inside Task "2" should be store as "int", not "const int&"
}
BaseTask* createTask2(const int& i, const int& j) {
return new Task<int, const int&>(&fun, i, j); // "j" must not be disposed at the time of task.run(), so inside Task "j" should be store as "int", not "const int&"
}
void test(){
createTask1()->run();
createTask2(1, 2)->run();
}
task will only be run no more then once, that is zero or one times.
You aren't allowed to use std::tuple::special_decay_t even if it exists: it is an implementation detail. That code on cppreference exists for exposition only: it works "as if" that type exists. If your implementation uses that code, that is an implementation detail that different compilers will not have, and the next iteration of your compiler is free to change/make private/rename/etc.
As exposition, it explains what you need to write if you want to repeat the special decay process of std::make_tuple and a few other C++11 interfaces.
As a first step, I'll keep your overall design, and repair it a touch. Then I'll point out an alternative.
MTArg... are the parameters of the function:
template<typename ... MTArg>
struct Task {
typedef void (*RawFunction)(MTArg...);
Here we want to forward some set of arguments into a tuple, but the arguments need not match MTArg -- they just have to be convertible:
template<typename ... Args>
explicit Task(RawFunction rawFunction, Args&&... args)
rawFunction(rawFunction),
args(std::make_tuple(std::forward<Args>(args)...)) {}
which the above checks. Note I made it explicit, as if Args... is empty, we don't want this to be a converting constructor.
void run() {
callFunction(GenIndexSequence<sizeof...(MTArg)>());
}
private:
template<unsigned int... argIndexs>
inline void callFunction() {
rawFunction(std::forward<MTArg>(std::get<argIndexs>(args))...);
}
RawFunction rawFunction;
std::tuple<MTArg...> args;
};
and then we write a make_task function:
template<typename ... MTArg, typename... Args>
Task<MTArg...> make_task( void(*raw)(MTArg...), Args...&& args ) {
return { raw, std::forward<Args>(args)... };
}
which looks something like that. Note that we deduce MTArg... from the function pointer, and Args... from the arguments.
Just because our function takes foo by value, does not mean we should make copies of it, or store an rvalue reference to it, or what have you.
Now, the above disagrees with how std::function and std::thread work, which is where special_decay_t comes in.
Usually when you store arguments to a function, you want to store actual copies, not references to possibly local variables or temporary variables that may go away. And if your function takes arguments by lvalue non-const reference, you want to take extra care at the call site that you aren't binding it to stack variables.
That is where reference_wrapper comes in and the special_decay_t bit: deduced arguments are decayed into literals, which have conventional lifetimes. Types packaged into std::reference_wrapper are turned into references, which lets you pass references through the interface.
I'd be tempted to duplicate the C++11 pattern, but force creators of a Task to explicitly reference_wrapper all types that are supposed to be passed by reference into the raw function.
But I am unsure, and the code to do that gets a touch messy.
Q1: is && after MTArg necessary
Task(RawFunction rawFunction, MTArg&& ... args) : // Q1: MTArg&& ... args
No, it is not necessary, since it is a concrete function (constructor in this case). It would matter if it was a template function, then args would be of universal reference type.
For the same reason, you do not need to use std::foward.
Q3: is type of args correct, do I need:
std::tuple<special_decay_t<MTArg>...>
Yes, because types should not be rvalues, if you want to store them in a tupple.

C++ One std::vector containing template class of multiple types

I need to store multiple types of a template class in a single vector.
Eg, for:
template <typename T>
class templateClass{
bool someFunction();
};
I need one vector that will store all of:
templateClass<int> t1;
templateClass<char> t2;
templateClass<std::string> t3;
etc
As far as I know this is not possible, if it is could someone say how?
If it isn't possible could someone explain how to make the following work?
As a work around I tried to use a base, non template class and inherit the template class from it.
class templateInterface{
virtual bool someFunction() = 0;
};
template <typename T>
class templateClass : public templateInterface{
bool someFunction();
};
I then created a vector to store the base "templateInterface" class:
std::vector<templateInterface> v;
templateClass<int> t;
v.push_back(t);
This produced the following error:
error: cannot allocate an object of abstract type 'templateInterface'
note: because the following virtual functions are pure within 'templateInterface'
note: virtual bool templateInterface::someFunction()
To fix this error I made the function in templateInterface not a pure virtual by providing a function body, this compiled but when calling the function the overide is not used, but instead the body in the virtual function.
Eg:
class templateInterface{
virtual bool someFunction() {return true;}
};
template <typename T>
class templateClass : public templateInterface{
bool someFunction() {return false;}
};
std::vector<templateInterface> v;
templateClass<int> i;
v.push_back(i);
v[0].someFunction(); //This returns true, and does not use the code in the 'templateClass' function body
Is there any way to fix this so that the overridden function is used, or is there another workaround to store multiple template types in a single vector?
Why your code doesn't work:
Calling a virtual function on a value doesn't use polymorphism. It calls the function which is defined for the type of this exact symbol as seen by the compiler, not the runtime type. When you insert sub types into a vector of the base type, your values will be converted into the base type ("type slicing"), which is not what you want. Calling functions on them will now call the function as defined for the base type, since not it is of that type.
How to fix this?
The same problem can be reproduced with this code snippet:
templateInterface x = templateClass<int>(); // Type slicing takes place!
x.someFunction(); // -> templateInterface::someFunction() is called!
Polymorphism only works on a pointer or reference type. It will then use the runtime type of the object behind the pointer / reference to decide which implementation to call (by using it's vtable).
Converting pointers is totally "safe" with regard to type slicing. Your actual values won't be converted at all and polymorphism will work as expected.
Example, analogous to the code snippet above:
templateInterface *x = new templateClass<int>(); // No type slicing takes place
x->someFunction(); // -> templateClass<int>::someFunction() is called!
delete x; // Don't forget to destroy your objects.
What about vectors?
So you have to adopt these changes in your code. You can simply store pointers to actual types in the vector, instead of storing the values directly.
When working with pointers you also have to care about deleting your allocated objects. For this you can use smart pointers which care about deletion automatically. unique_ptr is one such smart pointer type. It deletes the pointee whenever it goes out of scope ("unique ownership" - the scope being the owner). Assuming the lifetime of your objects is bound to the scope this is what you should use:
std::vector<std::unique_ptr<templateInterface>> v;
templateClass<int> *i = new templateClass<int>(); // create new object
v.push_back(std::unique_ptr<templateInterface>(i)); // put it in the vector
v.emplace_back(new templateClass<int>()); // "direct" alternative
Then, call a virtual function on one of these elements with the following syntax:
v[0]->someFunction();
Make sure you make all functions virtual which should be possible to be overridden by subclasses. Otherwise their overridden version will not be called. But since you already introduced an "interface", I'm sure you are working with abstract functions.
Alternative approaches:
Alternative ways to do what you want is to use a variant type in the vector. There are some implementations of variant types, the Boost.Variant being a very popular one. This approach is especially nice if you don't have a type hierarchy (for example when you store primitive types). You would then use a vector type like std::vector<boost::variant<int, char, bool>>
Polymorphism only works through pointers or references. You'll
need the non-template base. Beyond that, you'll need to decide
where the actual objects in container will live. If they're all
static objects (with sufficient lifetime), just using
a std::vector<TemplateInterface*>, and inserting with
v.push_back(&t1);, etc., should do the trick. Otherwise,
you'll probably want to support cloning, and keep clones in the
vector: preferably with Boost pointer containers, but
std::shared_ptr can be used as well.
The solutions given so far are fine though be aware that in case you were returning the template type other than bool in your example , none of these would help as the vtable slots would not be able to be measured before hand. There are actually limits , from a design point of view , for using a template oriented polymorphic solution.
Solution nr. 1
This solution inspired by Sean Parent's C++ Seasoning talk. I highly recommend to check it out on youtube. My solution simplified a bit and the key is to store object in method itself.
One method only
Create a class that will invoke method of stored object.
struct object {
template <class T>
object(T t)
: someFunction([t = std::move(t)]() { return t.someFunction(); })
{ }
std::function<bool()> someFunction;
};
Then use it like this
std::vector<object> v;
// Add classes that has 'bool someFunction()' method
v.emplace_back(someClass());
v.emplace_back(someOtherClass());
// Test our vector
for (auto& x : v)
std::cout << x.someFunction() << std::endl;
Several methods
For several methods use shared pointer to share object between methods
struct object {
template <class T>
object(T&& t) {
auto ptr = std::make_shared<std::remove_reference_t<T>>(std::forward<T>(t));
someFunction = [ptr]() { return ptr->someFunction(); };
someOtherFunction = [ptr](int x) { ptr->someOtherFunction(x); };
}
std::function<bool()> someFunction;
std::function<void(int)> someOtherFunction;
};
Other types
Primitive types (such as int, float, const char*) or classes (std::string etc.) may be wrapped in the same way as object class do but behave differently. For example:
struct otherType {
template <class T>
otherType(T t)
: someFunction([t = std::move(t)]() {
// Return something different
return true;
})
{ }
std::function<bool()> someFunction;
};
So now it is possible to add types that does not have someFunction method.
v.emplace_back(otherType(17)); // Adding an int
v.emplace_back(otherType("test")); // A string
Solution nr. 2
After some thoughts what we basically done in first solution is created array of callable functions. So why not just do the following instead.
// Example class with method we want to put in array
struct myclass {
void draw() const {
std::cout << "myclass" << std::endl;
}
};
// All other type's behaviour
template <class T>
void draw(const T& x) {
std::cout << typeid(T).name() << ": " << x << std::endl;
}
int main()
{
myclass x;
int y = 17;
std::vector<std::function<void()>> v;
v.emplace_back(std::bind(&myclass::draw, &x));
v.emplace_back(std::bind(draw<int>, y));
for (auto& fn : v)
fn();
}
Conclusion
Solution nr. 1 is definitely an interesting method that does not require inheritance nor virtual functions. And can be used to other stuff where you need to store a template argument to be used later.
Solution nr. 2, on the other hand, is simpler, more flexible and probably a better choice here.
If you're looking at a container to store multiple types, then you should explore boost variant from the popular boost library.