Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hold any kind of C++ template class in member variable

I have got two classes.

The first class (A) is builded with an template.

template <class T>
class A
{
    public:
        T value;
};

The second class (B) should have an object of class A as member variable. Like this:

class B
{
    public:
        A<int> value;
};

But now i want to use any kind of template-class in class A. Not only int. Apparent I can't declare a (member-)variable which contains any kind of a class. So, I need something like this:

class B
{
    public:
        A<*> value;
};

Is there any (clean) solution for this problem?

-- Greeting from Germany, Bastian

like image 405
user906756 Avatar asked Aug 22 '11 23:08

user906756


People also ask

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Can a non template class have a template member function?

A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.

Can a member function be a template?

Member functions can be function templates in several contexts. All functions of class templates are generic but aren't referred to as member templates or member function templates. If these member functions take their own template arguments, they're considered to be member function templates.

How would you define member function of template class?

Member functions of class templates (C++ only)You may define a template member function outside of its class template definition. The overloaded addition operator has been defined outside of class X . The statement a + 'z' is equivalent to a. operator+('z') .


1 Answers

You cannot have a single class B with "any" member object, because B has to be a well-defined class, and A<T> is a different type for different types T. You can either make B a template itself:

template <typename T>
class B
{
  A<T> value;
};

or you can take a look at boost::any, which is type-erasing container for arbitrary types (but making use of it requires a certain amount of extra work). The any class only works for value types, though, it's not completely arbitrary.

like image 184
Kerrek SB Avatar answered Nov 04 '22 08:11

Kerrek SB