samedi 11 juillet 2020

Is it possible to make template specialization for zero template arguments?

Let's suppose I have a class like that:

template <typename T>
struct S {
  int n = 1;
  S(T t) : n(t.m) {};
  S() = default;
};

Is it possible to change something so that it would be possible to instantiate S with no template arguments in case if I want to use the default constructor like that S s {};?

The best thing I came up with is to assign some bogus default value to the template argument so that it becomes optional:

#include <iostream>

struct default_ {};

template <typename T = default_>
struct S {
  int n = 1;
  S(T t) : n(t) {};
  S() = default;
};


int main() {
  S<int> s1 {10};
  std::cout << "Value:\n" << s1.n << std::endl;
  S s2 {};
  std::cout << "Value:\n" << s2.n << std::endl;
}

https://repl.it/repls/RegalCoolDeal

Aucun commentaire:

Enregistrer un commentaire