lundi 23 juillet 2018

Template specialisation with default argument

I have a program that is as follows. There is a base template struct X and a partial specialisation with SFINAE.

template <typename T, typename U = void>
struct X{
  X() {
    std::cout << "in 1" << std::endl;
  };
};

template <typename T>
struct X< T, std::enable_if_t<std::is_integral_v<T>> > {
  X() {
    std::cout << "in 2" << std::endl;
  };
};

int main() {
  X<int> x;
}

When running the program in 2 is printed.

  1. Why is it that the second specialisation is chosen over the first since both of them effectively declare a struct X<int, void>. What makes std::enable_if_t<std::is_integral_v<T>> more specialised than a default template type argument as shown in the base template?

  2. Why does the default type argument of the base template have to be the same as the type defined by the partial specialisation for the partial specialisation to be called and in 2 to be printed. Why does changing to std::enable_if_t<std::is_integral_v<T>, bool> cause the base template in 1 to be called?

Aucun commentaire:

Enregistrer un commentaire