Home How to store a template as a member of a typical C++ class
Reply: 1

How to store a template as a member of a typical C++ class

IllegalSkillsException Published in 2018-01-11 09:45:29Z

I am using C++ 14 where my code needs to build for clang, gcc & Microsoft compiler. I have a class like below

class MyClass {


    AnotherClass    m_member_object;
    int             m_some_value_1;
    int             m_some_value_2;

    MyClass(const AnotherClass & another_object, int some_value_1, int some_value_1) {

        m_member_object = another_object;
        m_some_value_1 = some_value_1;
        m_some_value_1 = some_value_2;

    MyClass(const MyClass & my_class_copy) {

        m_member_object = my_class_copy.m_member_object;
        m_some_value_1 = my_class_copy.m_some_value_1;
        m_some_value_2 = my_class_copy.m_some_value_2;

I want to templatise AnotherClass which is member object (or could be a pointer) in MyClass. Trying to learn templates from here, when I make AnotherClass like below,

template<typename T>
T  m_member_object;

Compiler complains that member m_member_object is declared as a template

How can I store a template type instead of AnotherClass & let the user code of MyClass define what type it wants to store in MyClass?

Caleth Reply to 2018-01-11 10:24:26Z

The type of each member has to be the same throughout the class.

You have two choices:

  • MyClass is one type, m_member_object is one type that boxes up all the required possible values, such as std::any. You then have to deal with unboxing it and only ever doing type-appropriate things to it

  • MyClass is multiple types, m_member_object is specific to each MyClass. This is typically done by making MyClass a template. You can template <typename T> MyClass<T> : MyClassBase and use virtual dispatch, which allows you to operate on one type in outside code, however you have to use some indirection (typically std::unique_ptr<MyClassBase>) to safely operate.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.339067 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO