Abhishek Modi
Abhishek Modi

Reputation: 197

Passing template classes as arguments

I have two template classes FibonacciHeap and Adapter. Both of them have the same interface.

template< typename PRIO, typename VALUE, typename CMP = std::less<PRIO> >
class FibonacciHeap;

template<typename PRIO,typename VALUE >
class BinaryHeap;

I have another function dijkstra. It can use either BinaryHeap<double,int> or FibonacciHeap<double,int> as its priority queue. I want to pass the type of priority queue as argument.

How can I do that? I know writing an abstract class is an option, but I don't really want to do that. I am looking for other options.

Upvotes: 0

Views: 1457

Answers (2)

MSalters
MSalters

Reputation: 180303

The previous answer is functionally good, but a bit unusual.

The usual solution avoids the argument:

template <class H> int dijkstra()
{
    H heap;
}

You call the function passing the intended heap type.

int dist0 = dijkstra<FibonacciHeap<double,int>>();
int dist1 = dijkstra<BinaryHeap<double,int>>();

As an alternative, use a template template parameter:

template <template H<class, class>> int dijkstra()
{
    H<double, int> heap;
}
int dist0 = dijkstra<FibonacciHeap>();
int dist1 = dijkstra<BinaryHeap>();

Upvotes: 2

usr1234567
usr1234567

Reputation: 23471

Make dijkstra a templated function.

template <class H>
int dijkstra(H heap)
{
  // just use heap
}

You can call this function like that:

FibonacciHeap<double,int> heapFibo;
BinaryHeap<double,int> heapBina;

int dist0 = dijkstra(heapFibo);
int dist1 = dijkstra(heapBina);

The template magic is done by the compiler.

Upvotes: 1

Related Questions