[英]Why this template constexpr function doesn't compile on gcc but works well on clang?
As you can see here http://melpon.org/wandbox/permlink/vJSyO14mkbH0MQRq this doesn't compile on gcc with the error: 如您在此处看到的http://melpon.org/wandbox/permlink/vJSyO14mkbH0MQRq,这不会在gcc上编译并显示以下错误:
prog.cc: In instantiation of 'constexpr B convert(A) [with A = unsigned char; B = short unsigned int]':
prog.cc:16:52: required from here
prog.cc:12:1: error: body of constexpr function 'constexpr B convert(A) [with A = unsigned char; B = short unsigned int]' not a return-statement
The code: 编码:
#include <stdint.h>
#include <limits>
#include <iostream>
template< typename A, typename B >
constexpr B convert( A a )
{
auto aMax = std::numeric_limits< A >::max();
auto bMax = std::numeric_limits< B >::max();
return a * ( bMax / aMax );
}
int main()
{
std::cout << convert< uint8_t, uint16_t >( 128 ) << std::endl;
return 0;
}
This code requires a C++14 feature called "Relaxing constraints on constexpr-functions". 此代码需要C ++ 14功能,称为“放松constexpr函数的约束”。 It is supported in Clang since version 3.4, but GCC didn't implement it yet and subsequently complains about your function template.
从3.4版开始,Clang就支持它,但是GCC 尚未实现它 ,因此抱怨您的函数模板。
There is no need for C++14 though, just rewrite it as 不过,不需要C ++ 14,只需将其重写为
template <typename B, typename A> //! Note that I reordered the parameters
constexpr B convert( A a )
{
return a * (std::numeric_limits< B >::max() / std::numeric_limits< A >::max());
}
You can also use alias declarations. 您也可以使用别名声明。
template <typename T, T v>
using iconst = std::integral_constant<T, v>;
template <typename B, typename A>
constexpr B convert( A a )
{
using aMax = iconst<A, std::numeric_limits< A >::max()>;
using bMax = iconst<B, std::numeric_limits< B >::max()>;
return a * (bMax::value / aMax::value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.