New*_*fer 0 c++ gcc clang c++14
正如你在这里看到的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
Run Code Online (Sandbox Code Playgroud)
代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
此代码需要一个名为"放宽约束constexpr函数"的C++ 14特性.它自版本3.4以来在Clang中得到支持,但GCC 尚未实现它,随后抱怨您的功能模板.
不需要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());
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用别名声明.
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
300 次 |
最近记录: |