c++ - Why this template constexpr function doesn't compile on gcc but works well on clang? -
as can see here http://melpon.org/wandbox/permlink/vjsyo14mkbh0mqrq doesn't compile on gcc error:
prog.cc: in instantiation of 'constexpr b convert(a) [with = unsigned char; b = short unsigned int]': prog.cc:16:52: required here prog.cc:12:1: error: body of constexpr function 'constexpr b convert(a) [with = unsigned char; b = short unsigned int]' not return-statement
the code:
#include <stdint.h> #include <limits> #include <iostream> template< typename a, typename b > constexpr b convert( a ) { auto amax = std::numeric_limits< >::max(); auto bmax = std::numeric_limits< b >::max(); homecoming * ( bmax / amax ); } int main() { std::cout << convert< uint8_t, uint16_t >( 128 ) << std::endl; homecoming 0; }
this code requires c++14 feature called "relaxing constraints on constexpr-functions". supported in clang since version 3.4, gcc didn't implement yet , subsequently complains function template.
there no need c++14 though, rewrite as
template <typename b, typename a> //! note reordered parameters constexpr b convert( a ) { homecoming * (std::numeric_limits< b >::max() / std::numeric_limits< >::max()); }
you can utilize alias declarations.
template <typename t, t v> using iconst = std::integral_constant<t, v>; template <typename b, typename a> constexpr b convert( a ) { using amax = iconst<a, std::numeric_limits< >::max()>; using bmax = iconst<b, std::numeric_limits< b >::max()>; homecoming * (bmax::value / amax::value); }
demo
c++ gcc clang c++14
No comments:
Post a Comment