k-a-v
k-a-v

Reputation: 347

Contain templated data without using templated class

I have the following basic structure:

template<typename T>
class A {
    T data;
};

class B {
    A data; // no template parameters
};

The data in class B can have any template parameters, but I do not want to template B, which would be one way to fix the fact that the declaration of A data has no parameters. Is there a way to do this, or must B be templated?

Upvotes: 1

Views: 195

Answers (2)

JeJo
JeJo

Reputation: 32847

Not a straight forward way, but you can do it using std::any(which required or later support) as the member of B class.

#include <any>
#include <type_traits>

template<typename T>
class A {
   T data;
};

// traits for checking template class instance of A
template <typename T> struct is_class_A : public std::false_type {};
template <typename T> struct is_class_A<A<T> > : public std::true_type {};

class B
{
   std::any mData;

public:
   // templates class constructor for any data
   template<typename T> B(T const& data)
      : mData{ data }
   {
      // to restrict B having the data other than A<T> s
      static_assert(is_class_A<T>::value);
   }
};

Now you could.

A<int> aObject;
B object{ aObject }; // works

// B object2{ 1 };   // compiler error

See live demo

Upvotes: 4

Azam Bham
Azam Bham

Reputation: 1399

In your code, A is not a class, it is a class template. Therefore, you cannot declare a variable of type A, since A is not a type. You must provide a template parameter for data in B:

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

// ---- OR ---- //

class B{
    A<int> data; //int is only an example, you can use any type
};

Upvotes: 3

Related Questions