Search code examples
c++templatesgeneric-programmingnullptr

c++ generic programming with templates and nullptr


Let's say that I have this generic function:

template<typename T>
void foo(T data) {
  if(data == nullptr)
   return;
  //...
}

The problem is that I can not really write something like that. If T is a primitive type or an object passed by value, I can not compare it with the nullptr.

On the other hand, what if T is a pointer to an int? I would like to be able to compare it with the nullptr.

Is there any way?


Solution

  • As @j_random_hacker suggested, just overload the foo() function. This way you have 2 differents behaviour depending of the type you pass to foo()

    template<typename T>
    void foo(T *data)
    {
      if(data == nullptr)
        return;
      //...
    }
    
    template<typename T>
    void foo(T data)
    {
      //...
    }