1

If a class contains a member that only has a templated constructor, of which the template arguments cannot be automatically deduced, how would one go about initializing it? For example, take the following two structures:

struct A {
  unsigned m_size;

  template<typename T>
  A() : m_size(sizeof(T)) {}
};

struct B {
    A m_sizeHolder;

    B() : m_sizeHolder<int>() {}             // error during compilation
    B(int) : template m_sizeHolder<int>() {} // error during compilation
};

int main()
{
  B b1{};
  B b2{1};
}

The constructor of B needs to initialize the A member, however it only provides a templated constructor. Complicating things further, my use case involves a enumeration based template argument, making the use of a dummy parameter not possible as far as I know:

enum class E {
  E1,
  E2
};

struct C {
  const E m_type;

  template<E e>
  C() : m_type(e) {}
};

struct D {
    C m_typeHolder;

    D() : m_typeHolder<E::E1>() {}             // error during compilation
    D(int) : template m_typeHolder<E::E2>() {} // error during compilation
};

int main()
{
  D d1{};
  D d2{1};
}

I am currently targeting C++14, though answers for other versions are welcome as well.

harrbharry
  • 71
  • 2
  • 3
    http://stackoverflow.com/questions/2786946/c-invoke-explicit-template-constructor – Mat Feb 17 '17 at 14:31
  • I suggest to make 'A' a plain struct/class, also the constructor, and then have the template constructor in class B, calling A's constructor with the size of the template type. – Rene Feb 17 '17 at 14:31
  • @Mat Can you post that link as the answer so I can vote for it? This is exactly what I was looking for. – harrbharry Feb 17 '17 at 14:35

0 Answers0