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
An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With