Default or zero value of unknown template type

烂漫一生 提交于 2021-01-27 05:12:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!