1

I wasn't able to find an answer by googling, since I don't know what to actually look for. So I stumbled across this:

template<typename T>
class SkipList {
    public:
        SkipList() : max_level_(16) { 
            head = new Node(T(), max_level_);
    ...
}

and I don't really know what T() means. I'm familiar with the concept of templates (at least I have basic knowledge about it), but I've never seen using the ()-Operator on them. So hat is it exactly doing?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
xotix
  • 494
  • 1
  • 13
  • 41

2 Answers2

3

What that is doing is creating a default object of that type. Depending on the object, it will mean different things, but what it comes down to is that when you want something there, but don't particularly care what it is, you can use a default object to get an object with generic values. For int and double it should be 0, but for more complex types like string, it becomes things like the empty string or all attributes are set to 0. This is part of the reason to have a default constructor in classes.

std::cout << int() << " " << std::string() << " " << double();

outputs:

0  0 
Hawkeye5450
  • 672
  • 6
  • 18
  • 3
    There is no "null string" in C++. Creating a `std::string` from `nullptr` (or `NULL`, or `0`) is undefined behaviour. You mean an *empty* string, which is something very different. – Christian Hackl Mar 31 '18 at 15:34
2

int() creates a default int (zero).

using Ptr = void*; Ptr() creates a default void* (a nullptr).

std::string() creates a default std::string (an empty string).

Do you see the pattern?

T() creates a default T and works for every type for which objects can be created without passing any arguments. If T is int, then you get a zero int. If T is void*, then you get a nullptr. If T is std::string, then you get an empty string. And so on.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62