Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to deduce types by template integers in C++

I have code:

template<int I, typename = void>
struct indexed_type {
  using type = void;
  indexed_type() { std::cout << "I is void: " << I << std::endl; }
};


template<int I>
struct indexed_type<I, typename std::enable_if<I == 1, char>::type> {
  using type = char;
  indexed_type() { std::cout << "I is char: " << I << std::endl; }
};

But after an initialization:

indexed_type<0>{};
indexed_type<1>{}; // not happens always

I have got not worked second variant always 🙁

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you help me to get working the second variant of specialization ?


Thanks

>Solution :

Your specialization will only be used if the second type is given and is char, like indexed_type<1, char>. Without specifying the second parameter, it defaults to void (indexed_type<1> is the same as indexed_type<1, void>, which does not select the second specialization).

You probably want to specialize based on the value of I:

template<int I>
struct indexed_type;

template<>
struct indexed_type<0> {
  using type = void;
  static constexpr int I = 0;
  indexed_type() { std::cout << "I is void: " << I << std::endl; }
};

template<>
struct indexed_type<1> {
  using type = char;
  static constexpr int I = 1;
  indexed_type() { std::cout << "I is char: " << I << std::endl; }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading