C++11 recursive templates - c++

I want to achive the following behavior.
In a base class I wish to have a container to store pointers to methods of derived class. (I want to store there h1 and h2).
Base class is also implementing methods allowing to store those pointers and the container itself
There is not any code ready yet, cause I wonder whether it's possible at all - eg:
template<typename E, typename S>
using Map = std::unordered_map<E, std::function<S* (S&, void)>>;
template<typename E, typename S>
class Base {
someFunctToPutPointersIntoMap() {}
Map<E, S> mEventMap;
}
template<typename E, typename S>
class Derived: public Base<E, S> {
public:
Derived* h1(void) {};
Derived* h2(void) {};
};
However how then I can declare object of derived class? For me its parameters are recursive eg.
Derived<E, Derived<E, Derived<E, Derived<E, ...etc... > object;
So it will never compile. I am sure there is some way to handle it, however I have none idea.

Related

derived method receiving const char * shadows base method receiving char [duplicate]

This has me wondering. Suppose I have :
class Base
{
public:
template<typename T>
void foo(T& varT)
{
//
}
template<typename T, typename U>
void foo(T& varT, U& varU)
{
//
}
};
class Child : public Base
{
public:
template<typename T, typename U, typename Z>
void foo(T& varT, U& varU, Z& varZ)
{
//
}
};
Now when I try this:
Child c;
char cVar;
int iVar;
float fVar;
c.foo(cVar);
c.foo<int>(cVar);
c.template foo<int>(cVar);
None of the calls work. They are always shadowed with error 'No matching member function for call'. Can anybody point me to a way to resolve this? I read in the standard that derived objects shadow template functions inherited but the standard explicitly said that the parameter list must be the same if they are shadowed.
Appreciate the help.
Hiding base members always happens when you have a name in a derived class that is present in a base class. The basic reason is that it is desirable to guard derived class uses against changes in the base class: assuming names from bases were not hidden, if a new overload in a base class is added a working look-up to a derived member may be hijacked to rather refer to the base class without any indication in the derived class that something may happen in the base class. If you mean to make the base members available, you can use a using declaration:
class Child : public Base
{
public:
using Base::foo; // declare that you want look up members from the base class
template<typename T, typename U, typename Z>
void foo(T& varT, U& varU, Z& varZ)
{
//
}
};
In your code you had three calls:
c.foo(cVar) works with the using declaration.
c.foo<int>(cVar) doesn't work even with the using declaration because you can't bind a non-const reference to int to a char lvalue. Using c.foo<char>(cVar) would work.
c.template foo<int>(cVar) suffers from the same problem. Since c is clearly not a dependent name, there is no need at all to use template in this context.
Without the using declaration you can call the member by qualifying the call explicitly, e.g.:
c.Base::foo(cVar);
You need this:
http://en.cppreference.com/w/cpp/language/using_declaration
Add to Child's definition:
using Base::foo;

Aggregate initialization of possibly trivially constructible type. Possible with hidden base class?

I'm trying to implement something like a compressed pair, and would like it to be trivially constructible. I tried to do it in the following way:
template<size_t N, typename T, bool inherit = std::is_class_v<T>>
struct PairElement;
template<size_t N, typename T>
struct PairElement<N, T, true> : public T{};
template<size_t N, typename T>
struct PairElement<N, T, false>{ T _hidden_value; };
template<typename A, typename B>
class Pair
: public PairElement<0, A>
, public PairElement<1, B>
{
public:
constexpr const A& first() const noexcept
{
if constexpr(std::is_class_v<A>)
return static_cast<const A&>(*this);
else
return PairElement<0, A>::_hidden_value;
}
};
Pair<float, int> pair { 0.5f, 10 };
In places where just the performance counts this does in fact benchmark better than std::pair in certain situations where the trivial constructability or the empty base class optimization can be used. However a big problem with this implementation is that it can only be aggregate initialized if the pair element base types are inheritted publically, which is anoying because than the functions of the pair elements can be called, etc. Is there a way to explicitly hide all the base functions and members, or is there a way to support the aggregate initialization without having public base types and not giving up the empty base class optimization or the trivial constructibility if A and B are trivially constructible?

Factory method for template classes

I have an issue I'm facing where I'm trying to build a factory function that,
given an ID and a type will return the correct (templated) subclass.
What this is trying to solve:
The id() values are sent across a network as soon as a connection is established, and specify to the receiver how a sequence of bytes are encoded. The receiver knows in advance the type T that it expects, but does not know how that type T is encoded on the wire until it gets this value. It also specifies how return values (of some type U, where U may or may not be the same type as T) should be marshalled when they are returned. This code is used generally, i.e. there are multiple senders/receivers that use/expect different types; the types used between a given sender/receiver pair are always fixed, however.
A basic sketch of the problem: we have a (simplified) base class that defines id()
template <typename T>
class foo
{
public:
virtual ~foo() { }
// Other methods
// This must return the same value for every type T
virtual std::uint8_t id() const noexcept = 0;
};
From there, we have some subclasses:
template <typename T>
class bar : public foo<T>
{
public:
std::uint8_t id() const noexcept override { return 1; }
};
template <typename T>
class quux : public foo<T>
{
public:
std::uint8_t id() const noexcept override { return 2; }
};
For the actual factory function, I need to store something that
erases the type (e.g. bar, quux) so that I can store the actual
creation function in a homogenous container.
Effectively, I want semantics that are roughly equivalent to:
struct creation_holder
{
// Obviously this cannot work, as we cannot have virtual template functions
template <typename T>
virtual foo<T>* build() const;
};
template <template <typename> class F>
struct create : public creation_holder
{
// As above
template <typename T>
foo<T>* build() const override
{
return new F<T>();
}
};
std::unordered_map<std::uint8_t, create*>& mapping()
{
static std::unordered_map<std::uint8_t, create*> m;
return m;
}
template <typename T, template <typename> class F>
bool register_foo(F<T> foo_subclass,
typename std::enable_if<std::is_base_of<foo<T>, F<T>>::value>::type* = 0)
{
auto& m = mapping();
const auto id = foo_subclass.id();
creation_holder* hold = new create<F>();
// insert into map if it's not already present
}
template <typename T>
foo<T>* from_id(std::uint8_t id)
{
const auto& m = mapping();
auto it = m.find(id);
if(it == m.end()) { return nullptr; }
auto c = it->second;
return c->build<T>();
}
I've played around with a number of ideas to try and get something with similar
semantics, but with no luck. Is there a way to do this (I don't care if the
implementation is significantly different).
Some utility types for passing around types and bundles of types:
template<class...Ts>
struct types_t {};
template<class...Ts>
constexpr types_t<Ts...> types{}; // C++14. In C++11, replace types<T> with types_t<T>{}. Then again, I don't use it.
template<class T>
struct tag_t {};
template<class T>
constexpr tag_t<T> tag{}; // C++14. In C++11, replace tag<T> with tag_t<T>{} below
Now we write a poly ifactory.
Here is an ifactory:
template<template<class...>class Z, class T>
struct ifactory {
virtual std::unique_ptr<Z<T>> tagged_build(tag_t<T>) const = 0;
virtual ~ifactory() {}
};
you pass in the tag you want to build and you get out an object. Pretty simple.
We then bundle them up (this would be easier in c++171, but you asked for c++11):
template<template<class...>class Z, class Types>
struct poly_ifactory_impl;
The one type case:
template<template<class...>class Z, class T>
struct poly_ifactory_impl<Z,types_t<T>>:
ifactory<Z, T>
{
using ifactory<Z, T>::tagged_build;
};
the 2+ case:
template<template<class...>class Z, class T0, class T1, class...Ts>
struct poly_ifactory_impl<Z,types_t<T0, T1, Ts...>>:
ifactory<Z, T0>,
poly_ifactory_impl<Z, types_t<T1, Ts...>>
{
using ifactory<Z, T0>::tagged_build;
using poly_ifactory_impl<Z, types_t<T1, Ts...>>::tagged_build;
};
We import the tagged_build method down into the derived classes. This means that the most-derived poly_ifactory_impl has all of the tagged_build methods in the same overload set. We'll use this to dispatch to them.
Then we wrap it up pretty:
template<template<class...>class Z, class Types>
struct poly_ifactory:
poly_ifactory_impl<Z, Types>
{
template<class T>
std::unique_ptr<Z<T>> build() const {
return this->tagged_build(tag<T>);
}
};
notice I'm returning a unique_ptr; returing a raw T* from a factory method is code smell.
Someone with a poly_ifactory<?> just does a ->build<T>() and ignores the tagged_ overloads (unless they want them; I leave them exposed). Each tagged_build is virtual, but build<T> is not. This is how we emulate a virtual template function.
This handles the interface. At the other end we don't want to have to implement each build(tag_t<T>) manually. We can solve this with the CRTP.
template<class D, class Base, template<class...>class Z, class T>
struct factory_impl : Base {
virtual std::unique_ptr<Z<T>> tagged_build( tag_t<T> ) const override final {
return static_cast<D const*>(this)->build_impl( tag<T> );
}
using Base::build;
};
template<class D, class Base, template<class...>class Z, class Types>
struct poly_factory_impl;
the 1 type case:
template<class D, class Base, template<class...>class Z, class T0>
struct poly_factory_impl<D, Base, Z, types_t<T0>> :
factory_impl<D, Base, Z, T0>
{
using factory_impl<D, Base, Z, T0>::tagged_build;
};
the 2+ type case:
template<class D, class Base, template<class...>class Z, class T0, class T1, class...Ts>
struct poly_factory_impl<D, Base, Z, types_t<T0, T1, Ts...>> :
factory_impl<D, poly_factory_impl<D, Base, Z, types_t<T1, Ts...>>, Z, T0>
{
using factory_impl<D, poly_factory_impl<D, Base, Z, types_t<T1, Ts...>>, Z, T0>::tagged_build;
};
what this does is write a series of tagged_build(tag_t<T>) overloads of the ifactory methods, and redirects them to D::build_impl(tag_t<T>), where D is a theoretical derived type.
The fancy "pass Base around" exists to avoid having to use virtual inheritance. We inherit linearly, each step implementing one tagged_build(tag<T>) overload. All of them dispatch downward non-virtually using CRTP.
Use looks like:
struct bar {};
using my_types = types_t<int, double, bar>;
template<class T>
using vec = std::vector<T>;
using my_ifactory = poly_ifactory< vec, my_types >;
struct my_factory :
poly_factory_impl< my_factory, my_ifactory, vec, my_types >
{
template<class T>
std::unique_ptr< vec<T> > build_impl( tag_t<T> ) const {
return std::make_unique< std::vector<T> >( sizeof(T) );
// above is C++14; in C++11, use:
// return std::unique_ptr<vec<T>>( new vec<T>(sizeof(T)) );
}
};
and an instance of my_factory satisfies the my_ifactory interface.
In this case, we create a unique ptr to a vector of T with a number of elements equal to sizeof(T). It is just a toy.
Live example.
The pseudo code design.
The interface has a
template<class T> R build
function. It dispatches to
virtual R tagged_build(tag_t<T>) = 0;
methods.
The Ts in question are extracted from a types_t<Ts...> list. Only those types are supported.
On the implementation side, we create a linear inheritance of CRTP helpers. Each inherits from the last, and overrides a virtual R tagged_build(tag_t<T>).
The implementation of tagged_build uses CRTP to cast the this pointer to a more-derived class and call build_impl(tag<T>) on it. This is an example of non-runtime polymorphism.
So calls go build<T> to virtual tagged_build(tag_t<T>) to build_impl(tag<T>). Users just interact with one template; implementors just implement one template. The glue in the middle -- the virtual tagged_build -- is generated from a types_t list of types.
This is about 100 lines of "glue" or helper code, and in exchange we get effectively virtual template methods.
1 in c++17 this becomes:
template<template<class...>class Z, class...Ts>
struct poly_ifactory_impl<Z,types_t<Ts...>>:
ifactory<Z, Ts>...
{
using ifactory<Z, Ts>::tagged_build...;
};
which is much simpler and clearer.
Finally, you can do something vaguely like this without a central list of types. If you know both the caller and the callee know the type you could pass a typeid or typeindex into the ifactory, pass a void* or something similar out over the virtual dispatch mechanism, and cast/check for null/do a lookup in a map to types.
The internal implementation would look similar to this one, but you wouldn't have to publish types_t as part of your formal (or binary) interface.
Externally, you would have to "just know" what types are supported. At runtime, you might get a null smart (or dumb, ick) pointer out if you pass in an unsupported type.
With a bit of care you could even do both. Expose an efficient, safe mechanism to get compile-time known types applied to a template. Also expose a "try" based interface that both uses the efficient compile-time known system (if the type matches) and falls back on the inefficient runtime checked on. You might do this for esoteric backwards binary compatibility reasons (so new software can connect over an obsolete interface to new or old API implementations and handle having an old API implementation dynamically).
But at that point, have you considered using COM?

enable class's member depending on template

I already know that you can enable (or not) a class's method using std::enable_if
for exemple:
template<size_t D, size_t E>
class Field
{
...
size_t offset(const std::array<float,D>& p) const
{
...
}
template<typename TT = size_t>
typename std::enable_if<D!=E, TT>::type
offset(const std::array<float,E>& p) const
{
return offset(_projection(p));
}
...
};
This helps not being able to call function that are invalid in a specific case as well as removing overloading errors ... which, to me, is very nice !
I'd like to go further and make some of my class's members being present only if the are needed. That way I would get an error if I try to use an objected which would have otherwise not been initiated
I tried to do
template<size_t D, size_t E>
class Field
{
...
template<typename TT = projectionFunc>
typename std::enable_if<D!=E, TT>::type _projection;
}
But the compiler tells me :
erreur: data member ‘_projection’ cannot be a member template
Is there any way to achieve what I want ?
Hold the data members in a separate class that you can then specialize as needed.
template<size_t D, size_t E>
class Field {
template<size_t, size_t> struct Field_Members {
int _projection;
};
template<size_t V> struct Field_Members<V, V> { };
Field_Members<D, E> m;
};
and then use m._projection etc.
Field_Members doesn't have to be a nested class template; you can move it outside if desired. It is also possible to have Field inherit from it, but then it'd be a dependent base, and you'd have to write this->_projection, so it doesn't save much typing.
AFAIK, this is not possible with a simple SFINAE inside the class template. You can, of course, have the type of the member dependent on a compile-time condition, i.e. via std::conditional, but not eliminate the member entirely.
What you can do, of course, is use another class template, such as
template<bool Condition, typename T> struct Has { T value; };
template<typename T> struct Has<false,T> {};
and declare a member (or base) of this type and access the object via Has<>::value:
typename<bool Condition>
class foo
{
Has<Condition, double> x; // use x.value (only if Condition==true)
};

Base class template member function shadowed in Derived class, albeit different parameter list

This has me wondering. Suppose I have :
class Base
{
public:
template<typename T>
void foo(T& varT)
{
//
}
template<typename T, typename U>
void foo(T& varT, U& varU)
{
//
}
};
class Child : public Base
{
public:
template<typename T, typename U, typename Z>
void foo(T& varT, U& varU, Z& varZ)
{
//
}
};
Now when I try this:
Child c;
char cVar;
int iVar;
float fVar;
c.foo(cVar);
c.foo<int>(cVar);
c.template foo<int>(cVar);
None of the calls work. They are always shadowed with error 'No matching member function for call'. Can anybody point me to a way to resolve this? I read in the standard that derived objects shadow template functions inherited but the standard explicitly said that the parameter list must be the same if they are shadowed.
Appreciate the help.
Hiding base members always happens when you have a name in a derived class that is present in a base class. The basic reason is that it is desirable to guard derived class uses against changes in the base class: assuming names from bases were not hidden, if a new overload in a base class is added a working look-up to a derived member may be hijacked to rather refer to the base class without any indication in the derived class that something may happen in the base class. If you mean to make the base members available, you can use a using declaration:
class Child : public Base
{
public:
using Base::foo; // declare that you want look up members from the base class
template<typename T, typename U, typename Z>
void foo(T& varT, U& varU, Z& varZ)
{
//
}
};
In your code you had three calls:
c.foo(cVar) works with the using declaration.
c.foo<int>(cVar) doesn't work even with the using declaration because you can't bind a non-const reference to int to a char lvalue. Using c.foo<char>(cVar) would work.
c.template foo<int>(cVar) suffers from the same problem. Since c is clearly not a dependent name, there is no need at all to use template in this context.
Without the using declaration you can call the member by qualifying the call explicitly, e.g.:
c.Base::foo(cVar);
You need this:
http://en.cppreference.com/w/cpp/language/using_declaration
Add to Child's definition:
using Base::foo;