Search code examples
c++classtemplatesmemberclass-template

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?


Solution

  • 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