Overriding multiple virtual functions in a variadic class template - c++

Let me just give a code example.
#include <iostream>
#include <utility>
#include <tuple>
template <typename Service>
struct SubscriberImpl {
virtual void handleService(Service const&) = 0;
};
template <typename...ServiceType>
struct Subscriber : SubscriberImpl<ServiceType>... {
};
struct IntService {};
struct FloatService {};
template <typename StatusUpdatePolicy, typename... ServiceType>
struct StatusUpdater : Subscriber<ServiceType...>
{
StatusUpdater(StatusUpdatePolicy const& statusUpdater)
: m_statusUpdater{statusUpdater}
{}
// wont work
void handleService(IntService const& service) override {
m_statusUpdater.updateService(service);
}
void handleService(FloatService const& service) override {
m_statusUpdater.updateService(service);
}
StatusUpdatePolicy m_statusUpdater;
};
struct DummyPolicy {
void updateService(IntService const& service) {
m_i = 42;
std::cout << m_i << "\n";
}
void updateService(FloatService const& service) {
m_f = 3.14f;
std::cout << m_f << "\n";
}
int m_i;
float m_f;
};
int main() {
StatusUpdater<DummyPolicy, IntService, FloatService> su(DummyPolicy{});
su.handleService(IntService{});
su.handleService(FloatService{});
}
Here Subscriber has a pure virtual function handleService(ServiceType const) for each template parameter in pack ServiceType.... So I have to override each one on StatusUpdater. Here, I have provided the ones I need by hand for IntService and FloatService, knowing I will be only needing those in this minimal example. But I want to be able to provide an override for whatever there is in the pack ServiceType.... All of them will call updateService method of the given policy anyways.
Please note that Subscriber comes from an external library and I cannot modify its definition.

You cannot put such implementations directly into the class, you have to inherit them (similarly to how Subscriber inherits from multiple SubscriberImpl instantiations). However, to override them all and still keep your class polymorphically usable as a Subscriber, you will have to inherit them "sequentially" instead of "in parallel." Additionally, the Curiously recurring template pattern can be used to give all the implementations access to the final overriding object:
template <class Self, class SubscriberClass, class... ServiceTypes>
struct StatusUpdaterOverride;
template <class Self, class SubscriberClass, class ThisType, class... RemainingTypes>
struct StatusUpdaterOverride<Self, SubscriberClass, ThisType, RemainingTypes...> : StatusUpdaterOverride<Self, SubscriberClass, RemainingTypes...>
{
void handleService(ThisType const& service) override
{
static_cast<Self*>(this)->m_statusUpdater.updateService(service);
}
using StatusUpdaterOverride<Self, SubscriberClass, RemainingTypes...>::handleService;
};
template <class Self, class SubscriberClass, class ThisType>
struct StatusUpdaterOverride<Self, SubscriberClass, ThisType> : SubscriberClass
{
void handleService(ThisType const& service) override
{
static_cast<Self*>(this)->m_statusUpdater.updateService(service);
}
};
template <class StatusUpdatePolicy, class... ServiceType>
struct StatusUpdater : StatusUpdaterOverride<StatusUpdater<StatusUpdatePolicy, ServiceType...>, Subscriber<ServiceType...>, ServiceType...>
{
StatusUpdater(StatusUpdatePolicy const& statusUpdater)
: m_statusUpdater{statusUpdater}
{}
StatusUpdatePolicy m_statusUpdater;
};
[Live example]

I can't see a solution to do exactly what you want. However you can achieve the same behavior without needing the virtuality at all. I initially thought about a CRTP solution just like #Angew's answer and then came up with another possibility:
You could edit your Subscriber class like this:
template <typename ServiceType>
class Subscriber {
public:
template <typename Handler>
void handleService(ServiceType const& service, Handler&& hdler) {
// Maybe give `updateService` a broader name that can extend to other service handlers
std::forward<Handler>(hdler).updateService(service);
}
};
With that, your client code becomes:
template <typename StatusUpdatePolicy, typename... ServiceType>
struct StatusUpdater : Subscriber<ServiceType>...
{
StatusUpdater(StatusUpdatePolicy const& statusUpdater)
: m_statusUpdater{statusUpdater}
{}
template <typename ServiceT>
void handleService(ServiceT const& service) override {
Subscriber<ServiceT>::handleService(service, m_statusUpdater);
}
StatusUpdatePolicy m_statusUpdater;
};

Related

C++ lambda as parameter with variable arguments

I want to create an event system that uses lambda functions as its subscribers/listeners, and an event type to assign them to the specific event that they should subscribe to. The lambdas should have variable arguments, as different kinds of events use different kinds of arguments/provide the subscribers with different kinds of data.
For my dispatcher, I have the following:
class EventDispatcher {
public:
static void subscribe(EventType event_type, std::function<void(...)> callback);
void queue_event(Event event);
void dispatch_queue();
private:
std::queue<Event*> event_queue;
std::map<EventType, std::function<void(...)>> event_subscribers;
};
No issues here, but when I go to implement the subscribe() function in my .cpp file, like this:
void EventDispatcher::subscribe(EventType event_type, std::function<void(...)> callback) {
... (nothing here yet)
}
The IDE shows me this:
Implicit instantiation of undefined template 'std::function<void (...)>'
Don't try to plop event callbacks with different parameter types directly into a single map.
Instead, create a template to store the callback (templated by the parameter types), and store pointers to its non-template base.
Here's how I would do it:
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <tuple>
#include <typeindex>
#include <typeinfo>
#include <type_traits>
#include <utility>
struct Event
{
virtual ~Event() = default;
};
struct Observer
{
virtual ~Observer() = default;
virtual void Observe(const Event &e) const = 0;
};
template <typename ...P>
struct BasicEvent : Event
{
std::tuple<P...> params;
BasicEvent(P ...params) : params(std::move(params)...) {}
struct EventObserver : Observer
{
std::function<void(P...)> func;
template <typename T>
EventObserver(T &&func) : func(std::forward<T>(func)) {}
void Observe(const Event &e) const override
{
std::apply(func, dynamic_cast<const BasicEvent &>(e).params);
}
};
// We need a protected destructor, but adding one silently removes the move operations.
// And adding the move operations removes the copy operations, so we add those too.
BasicEvent(const BasicEvent &) = default;
BasicEvent(BasicEvent &&) = default;
BasicEvent &operator=(const BasicEvent &) = default;
BasicEvent &operator=(BasicEvent &&) = default;
protected:
~BasicEvent() {}
};
class EventDispatcher
{
public:
template <typename E>
void Subscribe(typename E::EventObserver observer)
{
event_subscribers.insert_or_assign(typeid(E), std::make_unique<typename E::EventObserver>(std::move(observer)));
}
template <typename E>
void QueueEvent(E &&event)
{
event_queue.push(std::make_unique<std::remove_cvref_t<E>>(std::forward<E>(event)));
}
void DispatchQueue()
{
while (!event_queue.empty())
{
Event &event = *event_queue.front();
event_subscribers.at(typeid(event))->Observe(event);
event_queue.pop();
}
}
private:
std::queue<std::unique_ptr<Event>> event_queue;
std::map<std::type_index, std::unique_ptr<Observer>> event_subscribers;
};
struct EventA : BasicEvent<> {using BasicEvent::BasicEvent;};
struct EventB : BasicEvent<> {using BasicEvent::BasicEvent;};
struct EventC : BasicEvent<int, int> {using BasicEvent::BasicEvent;};
int main()
{
EventDispatcher dis;
dis.Subscribe<EventA>([]{std::cout << "Observing A!\n";});
dis.Subscribe<EventB>([]{std::cout << "Observing B!\n";});
dis.Subscribe<EventC>([](int x, int y){std::cout << "Observing C: " << x << ", " << y << "!\n";});
dis.QueueEvent(EventA());
dis.QueueEvent(EventB());
dis.QueueEvent(EventC(1, 2));
dis.DispatchQueue();
}
You could create your own version of std::function that accepts functions of any signature using type erasure. This will require some heavy lifting though. I will provide a solution for void functions which requires C++17, because we will use std::any.
I will walk you through the steps first and then provide a full solution in code.
First you create some function_traits that capture the number and type of arguments of any kind of function using template meta-programming. We can "borrow" from here.
Then you create a class VariadicVoidFunction that has a templated call operator.
This call operator creates a std::vector<std::any> and passes it to the invoke method of a member of VariadicVoidFunction, which is a (resource-owning smart) pointer of type VariadicVoidFunction::Concept.
VariadicVoidFunction::Concept is an abstract base class with a virtual invoke method that accepts std::vector<std::any>.
VariadicVoidFunction::Function is a class template, where the template parameter is a function. It stores this function as member and inherits VariadicVoidFunction::Concept. It implements the invoke method. Here, we can std::any_cast the vector elements back to the expected types, which we can extract using function_traits. This allows us to call the actual function with the correct argument types.
VariadicVoidFunction gets a templated constructor accepting any kind of function F. It creates an instance of type VariadicVoidFunction::Function<F> and stores it in an owning (smart) pointer.
#include <memory>
#include <vector>
#include <any>
// function_traits and specializations are needed to get arity of any function type
template<class F>
struct function_traits;
// ... function pointer
template<class R, class... Args>
struct function_traits<R(*)(Args...)> : public function_traits<R(Args...)>
{};
// ... normal function
template<class R, class... Args>
struct function_traits<R(Args...)>
{
static constexpr std::size_t arity = sizeof...(Args);
template <std::size_t N>
struct argument
{
static_assert(N < arity, "error: invalid parameter index.");
using type = typename std::tuple_element<N,std::tuple<Args...>>::type;
};
};
// ... non-const member function
template<class C, class R, class... Args>
struct function_traits<R(C::*)(Args...)> : public function_traits<R(C&,Args...)>
{};
// ... const member function
template<class C, class R, class... Args>
struct function_traits<R(C::*)(Args...) const> : public function_traits<R(C const&,Args...)>
{};
// ... functor (no overloads allowed)
template<class F>
struct function_traits
{
private:
using call_type = function_traits<decltype(&F::operator())>;
public:
static constexpr std::size_t arity = call_type::arity - 1;
template <std::size_t N>
struct argument
{
static_assert(N < arity, "error: invalid parameter index.");
using type = typename call_type::template argument<N+1>::type;
};
};
template<class F>
struct function_traits<F&> : public function_traits<F>
{};
template<class F>
struct function_traits<F&&> : public function_traits<F>
{};
// type erased void function taking any number of arguments
class VariadicVoidFunction
{
public:
template <typename F>
VariadicVoidFunction(F const& f)
: type_erased_function{std::make_shared<Function<F>>(f)} {}
template <typename... Args>
void operator()(Args&&... args){
return type_erased_function->invoke(std::vector<std::any>({args...}));
}
private:
struct Concept {
virtual ~Concept(){}
virtual void invoke(std::vector<std::any> const& args) = 0;
};
template <typename F>
class Function : public Concept
{
public:
Function(F const& f) : func{f} {}
void invoke(std::vector<std::any> const& args) override final
{
return invoke_impl(
args,
std::make_index_sequence<function_traits<F>::arity>()
);
}
private:
template <size_t... I>
void invoke_impl(std::vector<std::any> const& args, std::index_sequence<I...>)
{
return func(std::any_cast<typename function_traits<F>::template argument<I>::type>(args[I])...);
}
F func;
};
std::shared_ptr<Concept> type_erased_function;
};
You can use it like this:
#include <unordered_map>
#include <iostream>
int main()
{
VariadicVoidFunction([](){});
std::unordered_map<size_t, VariadicVoidFunction> map =
{
{0, VariadicVoidFunction{[](){ std::cout << "no argument\n"; }} },
{1, VariadicVoidFunction{[](int i){ std::cout << "one argument\n"; }} },
{2, VariadicVoidFunction{[](double j, const char* x){ std::cout<< "two arguments\n"; }} }
};
map.at(0)();
map.at(1)(42);
map.at(2)(1.23, "Hello World");
return 0;
}
no argument
one argument
two arguments
Demo on Godbolt Compiler explorer
Note that this is a prototypical solution to get you started. One downside is that all arguments will be copied into the std::any You could avoid this by passing pointers to std::any, but you have to be careful with lifetimes when you do this.
After the input from #joergbrech and #HolyBlackCat I made this
enum class EventType {
WindowClosed, WindowResized, WindowFocused, WindowLostFocus, WindowMoved,
AppTick, AppUpdate, AppRender,
KeyPressed, KeyRelease,
MouseButtonPressed, MouseButtonRelease, MouseMoved, MouseScrolled,
ControllerAxisChange, ControllerButtonPressed, ControllerConnected, ControllerDisconnected
};
class IEvent {
public:
IEvent(EventType event_type) {
this->event_type = event_type;
}
EventType get_event_type() {
return event_type;
}
private:
EventType event_type;
};
class IEventSubscriber {
public:
/**
* #param event The event that is passed to the subscriber by the publisher; should be cast to specific event
* */
virtual void on_event(IEvent *event) = 0;
EventType get_event_type() {
return event_type;
}
protected:
explicit IEventSubscriber(EventType event_type) {
this->event_type = event_type;
}
private:
EventType event_type;
};
class FORGE_API EventPublisher {
public:
static void subscribe(IEventSubscriber *subscriber);
static void queue_event(IEvent *event);
static void dispatch_queue();
private:
static std::queue<IEvent*> event_queue;
static std::set<IEventSubscriber*> event_subscribers;
};
I've tested it and I get the expected result from this solution. For the full code solution -> https://github.com/F4LS3/forge-engine
std::function has no specialization for variadic function types.
You likely want std::function<void()>.

is it posible to prohibit a cast?

Context:
I have been trying to use Dietmar Kühl's delegate class from this answer in a way that only the owner class could activate it, and I almost achieved it.
The code is the following:
// Example program
#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
class Entity;
struct EvArgs {
Entity* Origin;
EvArgs(){
}
};
template <typename Signature>
struct delegate;
template <typename Args>
struct delegate<void(Args*)>
{
struct base {
virtual ~base() {}
virtual void do_call(Args* args) = 0;
};
template <typename T>
struct call : base {
T d_callback;
template <typename S>
call(S&& callback) : d_callback(std::forward<S>(callback)) {}
void do_call(Args* args) {
this->d_callback(std::forward<Args*>(args));
return;
}
};
std::vector<std::unique_ptr<base>> d_callbacks;
std::vector<std::unique_ptr<base>> d_tmp_callbacks;
delegate(delegate const&) = delete;
void operator=(delegate const&) = delete;
public:
delegate() {
if (!std::is_base_of<EvArgs, Args>::value)
throw "specified type is not derived class from EvArgs\n";
}
~delegate() {
d_callbacks.clear();
d_tmp_callbacks.clear();
}
template <typename T>
delegate& operator+= (T&& callback) {
this->d_callbacks.emplace_back(new call<T>(std::forward<T>(callback)));
return *this;
}
template <typename T>
delegate& operator<< (T&& callback) {
this->d_tmp_callbacks.emplace_back(new call<T>(std::forward<T>(callback)));
return *this;
}
};
template<typename Signature>
struct action_delegate;
template<typename Args>
struct action_delegate<void(Args*)> : public delegate<void(Args*)>{
delegate<void(Args*)>& getBase(){
return *static_cast<delegate<void(Args*)>*>(this);
}
void operator()(Args* args) {
for (auto& callback : this->d_callbacks) callback->do_call(args);
for (auto& callback : this->d_tmp_callbacks) callback->do_call(args);
this->d_tmp_callbacks.clear();
delete args;
}
};
class instance{
private:
action_delegate<void(EvArgs*)> _collision;
public:
delegate<void(EvArgs*)>& collision = _collision.getBase();
};
int main(){
instance i;
i.collision << [](EvArgs* a){
std::cout << "random calling\n";
};
//i want to prohibit this:
(static_cast< action_delegate<void(EvArgs*)>& >(i.collision))(new EvArgs());
}
Problem:
As the action_delegate is a private member, only the instance class can call its activation with operator(). And as delegate is public, operator <<() and operator +=() are accessible outside the class.
The problem is that there is a way to cast delegate into action_delegate, thus it's possible to activate the delegate with operator() outside the class. I really want to avoid that.
The original creator of this concept is accessible through the link at the start of the commentary body.

Why is template parameter deduction not working with a variadic template class where only the first two parameters are specified?

I have a variadic template class which takes two fixed template parameters and additionally a variable list of parameters.
When I create an instance I want to specify the first two parameters and have the rest deduced from the arguments passed to the ctor.
But it does not work, the variadic part seems always to be empty. I can only create an instance when I specify all the types (including the ctor arguments).
Here is the code I used for testing:
#include <iostream>
#include <tuple>
#include <string>
class Service
{
public:
virtual void Serve() = 0;
};
class InterfaceA : public Service {};
class InterfaceB : public Service {};
class InterfaceC : public Service {};
class ImplementationA : public InterfaceA
{
virtual void Serve() override
{
std::cout << "Implementation A: <null>";
}
};
class ImplementationB : public InterfaceB
{
public:
ImplementationB(int x)
: m_x(x)
{}
virtual void Serve() override
{
std::cout << "Implementation B: " << std::to_string(m_x);
}
private:
int m_x = 0;
};
class ImplementationC : public InterfaceC
{
public:
ImplementationC(std::string str)
: m_str(str)
{}
virtual void Serve() override
{
std::cout << "Implementation C: " << m_str;
}
private:
std::string m_str;
};
template <typename Interface, typename Implementation, typename... CtorArgs>
class Wrapper
{
public:
Wrapper(CtorArgs&&... args)
: m_ctorArgs(std::make_tuple(std::forward<CtorArgs>(args)...))
{}
Service& GetService()
{
m_service = std::apply([](CtorArgs ... ctorArgs)
{
return std::make_unique<Implementation>(ctorArgs...);
},
m_ctorArgs);
return *m_service;
}
private:
std::tuple<CtorArgs ...> m_ctorArgs;
std::unique_ptr<Service> m_service;
};
// deduction guide, not working...
template <typename Interface, typename Implementation, typename... CtorArgs>
Wrapper(int x)->Wrapper<Interface, Implementation, int>;
int main()
{
Wrapper<InterfaceA, ImplementationA> wrapperA;
wrapperA.GetService().Serve();
std::cout << "\n";
// Wrapper<InterfaceB, ImplementationB> wrapperB(7); // NOT OK
Wrapper<InterfaceB, ImplementationB, int> wrapperB(7); // OK
wrapperB.GetService().Serve();
std::cout << "\n";
}
I want to specify services, but create them on demand, when they are needed (due to dependencies between services). I already use factory methods in production code (wrappers which know what parameters to pass to service ctor), but in test code, I want to be able to quickly create a wrapper for mocks and dummy services, which might need different parameters as the production service.
I also tried to specify a deduction guide, but it seems to have no effect...
You might use template constructor, and std::function as factory:
template <typename Interface, typename Implementation>
class Wrapper
{
public:
template <typename... CtorArgs>
Wrapper(CtorArgs&&... args)
: m_factory([=](){return std::make_unique<Implementation>(ctorArgs...);})
{}
Service& GetService()
{
m_service = m_factory();
return *m_service;
}
private:
std::function<std::unique_ptr<Service>()> m_factory;
std::unique_ptr<Service> m_service;
};
Deduction guide is useless as it should be used to deduce all parameters.
It is all or nothing for providing template parameters.
But you could do:
Wrapper<InterfaceB, ImplementationB> wrapperB(7); // Ok
The deduction guide "should" be
template<typename Interface, typename Implementation, typename... CtorArgs>
Wrapper(CtorArgs&&... x)->Wrapper<Interface, Implementation, CtorArgs...>;
but this doesn't work, since Interface and Implementation are non-deducible.
I'd recommend following the standard library and using a factory function instead:
template<typename Interface, typename Implementation, typename... Args>
Wrapper<Interface, Implementation, Args...> make_wrapper(Args&&... args) {
return Wrapper<Interface, Implementation, Args...>(std::forward<Args>(args)...);
}
int main() {
auto wrapperA = make_wrapper<InterfaceA, ImplementationA>();
wrapperA.GetService().Serve();
std::cout << "\n";
}
Another solution is to add dummy parameters to Wrapper::Wrapper
template<typename T>
struct type_t { };
template<typename T>
constexpr inline type_t<T> type{};
template<typename Interface, typename Implementation, typename... CtorArgs>
class Wrapper {
public:
Wrapper(type_t<Interface>, type_t<Implementation>, CtorArgs&&... args)
: m_ctorArgs(std::make_tuple(std::forward<CtorArgs>(args)...))
{}
// ...
};
// not needed anymore, is implicit
// template<typename Interface, typename Implementation, typename... CtorArgs>
// Wrapper(type_t<Interface>, type_t<Implementation>, CtorArgs&&... x)->Wrapper<Interface, Implementation, CtorArgs...>;
int main() {
Wrapper wrapperB(type<InterfaceB>, type<ImplementationB>, 7);
wrapperB.GetService().Serve();
std::cout << "\n";
}
There's also this OCaml inspired thing:
template<typename Interface, typename Implementation>
struct Wrapper {
template<typename... Args>
class type {
public:
type(Args&&... args)
: m_ctorArgs(std::make_tuple(std::forward<Args>(args)...))
{}
// ...
};
};
int main() {
std::string s("Hello!");
// There's a spot of weirdness here: passing s doesn't work because then you end up trying to store a reference to s in the tuple
// perhaps the member tuple should actually be std::tuple<std::remove_cvref<Args>...>
Wrapper<InterfaceC, ImplementationC>::type wrapperC(std::move(s));
wrapperC.GetService().Serve();
std::cout << "\n";
}
Side note: Service::~Service() should probably be virtual.

C++ generic way to define multiple functions with a template

In C++ is it possible to define multiple methods based of the number of template parameters provided? Similar to how variadic functions work?
With functions I can do
template <class ...Args>
struct VariadicFunctionCallback {
typedef std::function<void(std::shared_ptr<Args>...)> variadic;
};
But what I want to know is if I could do something similar but to create multiple functions instead of multiple arguments
template <class ...FunctionArg>
class Example {
void Function(FunctionArg)...
}
Which would then allow me to do something like
template <>
class Example<int, float> {
void Function(int i) {
...
}
void Function(float f) {
...
}
}
And if this is possible what are the advantages over my current setup which is like
template<class EventType>
class EventHandler {
public:
void HandleEvent(const std::shared_ptr<EventType>& event) {
}
};
class ExampleEvent : public Event<ExampleEvent> {
};
class ExampleHandler : public EventHandler<ExampleHandler>, EventHandler<Events::ShutdownEvent> {
public:
void HandleEvent(const std::shared_ptr<ExampleEvent> &event);
void HandleEvent(const std::shared_ptr<Events::ShutdownEvent> &event);
};
--Edit--
I ended up with a mix if the two solutions.
It is probably not the best and I will continue to play around with and improve it overtime.
template <class EventType>
class BaseEventHandler {
public:
EventIdentifier GetIdentifier() const {
return EventType::GetIdentifier();
}
virtual void HandleEvent(const std::shared_ptr<EventType> &event) = 0;
};
template<class EventType, class ...EventTypes>
class EventHandler: public BaseEventHandler<EventTypes>... {
};
Which then allows me to do
class EventListener: public EventHandler<ShutdownEvent, MousePosEvent, WindowCloseRequestEvent> {
void HandleEvent(const std::shared_ptr<ShutdownEvent> &event);
void HandleEvent(const std::shared_ptr<MousePosEvent> &event);
void HandleEvent(const std::shared_ptr<WindowCloseRequestEvent> &event);
}
I suppose you can make Example a sort of recursive self-inheritancing class; something as
template <typename ...>
struct Example
{
// dummy Function() to end the recursion
void Function ()
{ }
};
template <typename T0, typename ... Ts>
struct Example<T0, Ts...> : public Example<Ts...>
{
using Example<Ts...>::Function;
void Function (T0 const &)
{ };
};
So you can write
int main ()
{
Example<int, long, float> e0;
e0.Function(0);
e0.Function(0L);
e0.Function(0.0f);
}
-- EDIT --
The OP ask
Could a specialisation then be preformed on top of this?
Do you mean something as follows?
template <typename ...>
struct Example
{
// dummy Function() to end the recursion
void Function ()
{ }
};
template <typename T0, typename ... Ts>
struct Example<T0, Ts...> : public Example<Ts...>
{
using Example<Ts...>::Function;
void Function (T0 const &)
{ };
};
template <typename ... Ts>
struct Example<float, Ts...> : public Example<Ts...>
{
void FunctionFloat (float const &)
{ };
};
int main ()
{
Example<int, long, float> e0;
e0.Function(0);
e0.Function(0L);
e0.FunctionFloat(0.0f);
//e0.Function(0.0f); // compilation error
}
This answer start's with max66's answer, more or less
We start with a class that uses recursive inheritance to implement our function. In my case, I chose operator(), and I used a variadic using declaration to bring all children operator() into scope:
namespace detail{
template<class T, class... U>
struct ExampleImpl : ExampleImpl<U>...{
using ExampleImpl<U>::operator()...;
void operator()(T _arg){/*...*/}
};
}
Where my answer diverges from max66's is in that we'll use this ExampleImpl class to compose our Example class:
template<class... T>
class Example
{
public:
template <class U>
void Function(U arg)
{
impl(arg);
}
void Function(float arg)
{
/*Your specialization code*/
}
private:
detail::ExampleImpl<T...> impl;
};
I do it this way for 2 reasons:
This inheritance is an implementation-detail and something you'd want to hide from clients.
*Now we can easily specialize our Function function for whatever type we want because we always have a choice in whether to call through to our instance of ExampleImpl or not.
Demo
If ExampleImpl needs to use member variables of your Example class, then you can either turn ExampleImpl into a full-fledged PIMPL class, or modify its constructor or operator() to accept additional arguments as a form of Dependency Injection
*You could just as easily perform full class specialization where float is one of the template parameters in the specialization, and define your own Function. Or you could use a form of tag dispatching to hide the float version unless it was in the list of template types.
Tag dispatch demonstration

Partial function/method template specialization workarounds

I know partial template specialization isn't supported for functions and class methods, so my question is: What are common solutions or patterns to resolve this? Below Derived derives from Base, and both of these classes have virtual methods greet() and speak(). Foo's holds a std::array<unique_ptr<T>, N> and is used in do_something(). Foo has two template parameters: T (the class type) and N (number of elements of the std::array) If N = 2, there exists a highly optimized version of do_something(). Now assume that Foo's T parameter isn't always the base class Base. Ideally, I would like to write the following code, but it's illegal:
//ILLEGAL
template<typename T>
void Foo<T,2>::do_something()
{
arr_[0]->greet();
}
Below is the full code and my current (ugly) solution. I have to specialize do_something() twice, once for Base and once for Derived. This gets ugly if there exists multiple methods like do_something() that can be optimized on the special N=2 case, and if there exists many subclasses of Base.
#include <iostream>
#include <memory>
class Base
{
public:
virtual void speak()
{
std::cout << "base is speaking" << std::endl;
}
virtual void greet()
{
std::cout << "base is greeting" << std::endl;
}
};
class Derived : public Base
{
public:
void speak()
{
std::cout << "derived is speaking" << std::endl;
}
void greet()
{
std::cout << "derived is greeting" << std::endl;
}
};
template<typename T, int N>
class Foo
{
public:
Foo(std::array<std::unique_ptr<T>, N>&& arr) :
arr_(std::move(arr))
{
}
void do_something();
std::array<std::unique_ptr<T>, N> arr_;
};
template<typename T, int N>
void Foo<T,N>::do_something()
{
arr_[0]->speak();
}
//Want to avoid "copy-and_paste" of do_something() below
template<>
void Foo<Base,2>::do_something()
{
arr_[0]->greet();
}
template<>
void Foo<Derived,2>::do_something()
{
arr_[0]->greet();
}
int main()
{
constexpr int N = 2;
std::array<std::unique_ptr<Derived>, N> arr =
{
std::unique_ptr<Derived>(new Derived),
std::unique_ptr<Derived>(new Derived)
};
Foo<Derived, N> foo(std::move(arr));
foo.do_something();
return 0;
}
The trick is to forward implementation to an helper template class, and partial specialize that class and/or use tag dispatching:
namespace {
template<typename T, int N, bool isBase = std::is_base_of<Base, T>::value>
struct helper {
// general case:
void operator () (std::array<std::unique_ptr<T>, N>& arr_) const
{
arr_[0]->speak();
}
};
template<typename T>
struct helper<T, 2, true>
{
void operator () (std::array<std::unique_ptr<T>, 2>& arr_) const
{
arr_[0]->greet();
}
};
// You may add other specialization if required.
}
template<typename T, int N>
void Foo<T,N>::do_something()
{
helper<T, N>()(arr_);
}
There are different alternatives, depending on how other constrains in the problem one might be more appropriate than another.
The first one is to forward the request to a static function in a template class, which allows for partial specializations:
template <int N>
struct Helper {
template <typename T>
static void talk(T& t) { // Should be T const &, but that requires const members
t.speak();
}
};
template <>
struct Helper<2> {
template <typename T>
static void talk(T& t) {
t.greet();
}
}
;
Then the implementation of do_something would be:
template <typename T, int N>
void Foo<T,N>::do_something() {
Helper<N>::talk(*arr_[0]);
}
Alternatively, you can use tag dispatch to select one of multiple overloads:
template <int N> struct tag {};
template <typename T, int N>
template <int M>
void Foo<T,N>::do_something_impl(tag<M>) {
arr_[0]->speak();
}
template <typename T, int N>
void Foo<T,N>::do_something_impl(tag<2>) {
arr_[0]->greet();
}
template <typename T, int N>
void Foo<T,N>::do_something() {
do_something_impl(tag<N>());
}
Where I have created a tag-type that can be specialized for any possible N. You could also use existing tools in C++11.
Finally, if you need to do something like this for different functions, you can use inheritance, and push some of the functionality to a base that resolves the differences. This can be done by either pushing common code to a base, differences to an intermediate level and using a lower level front type that just inherits from the rest (base contains generic code, derived types specialize). Or alternatively with CRTP (base(s) contain differences, derived type generic code and pulls specific implementations from the bases.