Is it possible to make template specialization for zero template arguments?
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