Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a template class as an argument to a function

Tags:

c++

templates

If I define a class using a template such as

template<class K, class V>
class myclass {
...
};

is there a way to pass objects defined by myclass to functions without using a template for the function? In order words, for every function that accepts myclass objects, does it also need to be defined using template< class K, class V> ?

The main reason for this is that I would like define a set of static functions that act on myclass objects so that I may limit the scope of these functions within their cpp files and not in header files.

like image 634
entitledX Avatar asked Sep 17 '11 23:09

entitledX


2 Answers

Make your template class inherit from some base class:

template<class K, class V>
class myclass : mybaseclass { ... };

where the base class declares the public functionality of the template as pure virtual. This way you only have one function rather than one function for each K, V combination.

like image 162
David Hammen Avatar answered Nov 02 '22 21:11

David Hammen


No, you cannot. A class template is not a class -- it is only a template. Only once you plug in the template parameters do you get a type, and for each different set of parameters you get a different, unrelated type.

Perhaps it's feasible for you to run some sort of type-erasing scheme, whereby you have a single container class which contains an abstract member pointer, and for each type you instantiate a concrete derived object. (Check out Boost.any.)

A bit like this:

class MyClassHolder { };

template <typename K, typename V>
class MyClassConcrete {  };

class MyClass
{
  MyClassHolder * p;

public:
  template <typename K, typename V> init(...)  // could be a constructor
  {
    p = new MyClassConcrete<K, V>();
  }
};

Now you can make your function accept a MyClass, but you have to add enough virtual functions to MyClassHolder, implement them in MyClassConcrete and expose them in MyClass that you can realise all your desired semantics.

like image 24
Kerrek SB Avatar answered Nov 02 '22 20:11

Kerrek SB