考虑(文件名是 hello.cpp)这段代码;这个想法是设计一个安全的数字类型转换而不会丢失或溢出。(我正在将一些代码从 MSVC 移植到 g++)。
#include <cstdint>
#include <iostream>
template<
typename T/*the desired type*/,
typename/*the source type*/ Y
> T integral_cast(const Y& y)
{
static_assert(false, "undefined integral cast");
}
// Specialisation to convert std::uint32_t to double
template<>
inline double integral_cast(const std::uint32_t& y)
{
double ret = static_cast<double>(y);
return ret;
}
int main()
{
std::uint32_t a = 20;
double f = integral_cast<double>(a); // uses the specialisation
std::cout << f;
}
当我通过键入使用 gcc 8.3 进行编译时,g++ -o hello hello.cpp
我得到了错误error: static assertion failed: undefined integral cast
。
这意味着 g++ 总是在编译未使用的模板代码。
请注意,MSVC 编译了这个(这很好,因为它允许我发现我没有考虑过的任何完整的演员特化)。
显然我错过了一些东西。但是什么?