Quantcast
Channel: handling void type in template - Stack Overflow
Viewing all articles
Browse latest Browse all 6

Answer by Criminal_Affair_At_SO for handling void type in template

$
0
0

Late to the party, especially since C++17 if constexpr solves this perfectly, but if you are limited to C++11, here is my solution:

  • For the variable, use a type helper:
template <typename T> struct remove_void { using type = T; };template <> struct remove_void<void> { using type = int; };remove_void<T>::type result;
  • For the assignment, use a function helper (this uses std::function but it works with a plain C pointer too):
template <typename RET, typename ...ARGS> inline void novoid_call(const std::function<RET(ARGS...)> &fn, RET &ret, const ARGS & ...args) {  ret = fn(args...);}template <typename ...ARGS> inline void novoid_call(const std::function<void(ARGS...)> &fn, int &ret, const ARGS & ...args) {  fn(args...);}novoid_call(Func, result);
  • For the return, use a static_cast:

(from Using template for return value. how to handle void return?)

return static_cast<T>(result);

Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>