Sebastian Green
Sebastian Green

Reputation: 51

C++ Reference to templated function

I have a templated class with several different instances which I would like to reference with a common type:

template <int par>
class Worker
{
public:
   int foo() { return m_par; }
   
private:
   static constexpr int m_par = par;
};

class B
{
private:
   Worker<10> m_worker1;
   Worker<20> m_worker2;
   Worker<30> m_worker3;
};

I can obviously define a reference to m_worker1:

const Worker<10>& ref = m_worker1;

But I am looking in a way to change the type of this reference (or maybe a pointer) in a way that it can refer to any of the instances of the templated class Worker, i.e being able to set it pointing to m_worker1, m_worker2 or m_worker3.

What type would work here? auto, void* or another deduction? I am using C11.

Upvotes: 0

Views: 63

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Worker is a class template. It is a template. It is not a class. To create an instance you first instantiate the template: Worker<10> is a class. Worker<20> is a different distinct class. As those are two types that have nothing in common there is no type that would allow you to store a reference to object of either type.

You can add a common base class:

struct Worker_base {};


template <int par>
class Worker : public Worker_base 
{
public:
   int foo() { return m_par; }
   
private:
   static constexpr int m_par = par;
};


int main() {
   Worker<10> m_worker1;
   Worker<20> m_worker2;
   Worker<30> m_worker3;

   Worker_base& m1 = m_worker1;
}

You could implement methods common to all workers in the base.


What type would work here? auto, [...]

auto is not a type. It is merely a placeholder you can use when the compiler can deduce the type. When there is no common type then auto does not help either.

[...] void* [...]

Do not use void*. C++ has better alternatives for type erasure. There is std::any to hold any type and std::variant for a limited set of possible types.

I am using C11.

I suppose you mean C++11. C11 is the C standard from 2011. std::any and std::variant are both C++17. Consider to upgrade to a more recent standard if you want to use them rather than polymorphism via inheritance.

Upvotes: 1

Related Questions