为什么这个模板 constexpr 函数不能在 gcc 上编译,但在 clang 上效果很好?
Why this template constexpr function doesn't compile on gcc but works well on clang?
如您所见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
代码:
#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;
}
此代码需要一个名为"放宽constexpr函数的约束"的C++14特性。Clang从3.4版本开始支持它,但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());
}
您也可以使用别名声明。
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);
}
演示
相关文章:
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 编译在我的 Mac 上工作,但在集群 (Linux) 上不起作用
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 在Visual Studio中使用括号时编译错误,但在G ++ / CLang ++中传递
- 带有引用的std::tuple在clang中编译失败,但在gcc中编译失败
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 我有一个C++函数,它在Dev C++中编译,但在G++中不编译
- Lua :在原生lua中编译,但在使用LuaJIT和sol2时C++出错
- 分配给静态变量的局部变量;编译错误在'c'但在 C++ 中成功
- 运行程序时找不到共享对象库,但在编译过程中链接了它
- C++代码编译,但在 Zorin OS 上运行时显示错误
- 为什么在编译过程中尽管有 -I(破折号大写 i)标志,但仍会出现未定义的引用错误?
- 我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
- Cmake Mac OSX库链接问题:在Linux上进行编译,但在Mac上进行了编译
- cmake cuda在Windows上单独的编译静态LIB链接错误,但在Ubuntu上没有
- strcpy 在 Windows 上编译,但在 Linux 上不编译
- 在 Windows 上编译错误 C2131 和 C3863,但在 Linux 上不编译错误
- 相同的代码在 Dev C++ 上编译,但在 Visual Studio 2017 上不编译
- 我正在尝试编写一个函数来计算C++数字的数字根,但在编译后出现错误
- CPP 文件运行,但在编译为 exe 时不起作用