Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default or zero value of unknown template type

Assuming the template function

template<typename T>
T foo(){
  // ...
  // Error occured
  if(error)
     return 0;
  // ...
}

which should return 0, 0.0f, nullptr, ... depending on the type T, when an error occured.

How to get the 0 of a unknown template type? in C# you can write default(T) to do this.

How to perform this in C++?

like image 885
Matthias Avatar asked Jun 26 '16 13:06

Matthias


1 Answers

You can use value initialization like return T(); or return T{}; (since C++11), or just return {}; (see list initialization (since C++11)) to return the default value of T.

like image 85
songyuanyao Avatar answered Sep 28 '22 07:09

songyuanyao