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

Viewed 1219

Let's suppose I have a class like that:

template <typename T>
struct S {
  int n = 1;
  S(T t) : n(t) {};
  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

2 Answers

If T is used only for the constructor, you don't need to template the whole class:

#include <iostream>

struct S {
  int n = 1;

  template <typename T>
  S(T t) : n(t) {};

  S() = default;
};

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

You might specialize S for void and create a CTAD https://en.cppreference.com/w/cpp/language/class_template_argument_deduction

#include <iostream>

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

template <>
struct S<void> {
  int n = 1;
  S() = default;  // only default
};

// CTAD calls to constructor S() will instantiate as S<void> 
template<typename... T> S() -> S<void>;   

int main() {
  S<int> s1 {10};
  std::cout << "Value:\n" << s1.n << std::endl;
  S s2 {};  // here CTAD will be trigged
  std::cout << "Value:\n" << s2.n << std::endl;
}

A link to cppinsights may help understand what and where things are being instantiated: https://cppinsights.io/s/8f0f4bf6

Related