Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template add/enable constructor based on template argument

Is it possible in the following scenario to define dedicated constructors for certain specializations of a template:

template<typename T, size_t D>
class vector {
  T values[D];
public:
  vector();
};

Constructors I want to add dependent on the D-argument:

template<typename T>
vector<T, 2>::vector(T t1, T t2) { ... }

template<typename T>
vector<T, 3>::vector(T t1, T t2, T t3) { ... }

template<typename T>
vector<T, 4>::vector(T t1, T t2, T t3, T t4) { ... }
like image 953
MFH Avatar asked Dec 11 '25 13:12

MFH


1 Answers

template<bool B>
using EnableIfB = typename std::enable_if<B, int>::type;

template<typename T, size_t D>
class vector {
  T values[D];
public:
  template<size_t D1 = D, EnableIfB<D1 == 2> = 0>
  vector(T t1, T t2) { ... }

  template<size_t D1 = D, EnableIfB<D1 == 3> = 0>
  vector(T t1, T t2, T t3) { ... }

  template<size_t D1 = D, EnableIfB<D1 == 4> = 0>
  vector(T t1, T t2, T t3, T t4) { ... }
};

Hope this helps.

like image 156
Johannes Schaub - litb Avatar answered Dec 13 '25 04:12

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!