Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

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

like image 644
Gill Bates Avatar asked Jul 11 '20 09:07

Gill Bates


People also ask

Are template specializations inline?

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.

What is meant by template specialization?

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.

Can a template be a template parameter?

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.

What are non-type parameters for templates?

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.


1 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;
}
like image 145
H Krishnan Avatar answered Oct 18 '22 11:10

H Krishnan