simpleroseinc

Logo

Developer Tips

View Company GitHub Profile

5 April 2020

Passing type parameter to constructor

by Zhihao Yuan

If a constructor needs to receive a type parameter without deduction, a template-argument-list inside angle brackets is not for that purpose. For example, given

class storage
{
  public:
    template<class T>
    explicit storage(size_t n);
};

The syntax storage<byte> meant to refer to a specialization of a class template called “storage.”

In such a case, you may encode a type parameter into an empty object with std::type_identity,

class storage
{
  public:
    template<class T>
    explicit storage(std::type_identity<T>, size_t n);
};

and select the constructor as follows:

auto obj = storage(std::type_identity<byte>(), 128);

You may also use std::in_place_type<T> if you meant to construct an object of type T inside your class that does not depend on T.

tags: cplusplus - constructor - type-parameter