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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With