问题
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++?
回答1:
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
.
来源:https://stackoverflow.com/questions/38038860/default-or-zero-value-of-unknown-template-type