非类型模板参数浮点数支持 ​

什么是非类型模板参数浮点数支持 ​

C++20 之前,非类型模板参数(NTTP)只能使用整数类型、枚举、指针、引用等,不能使用浮点数。这意味着你无法写出 template<double D> 这样的模板。

C++20 放宽了这个限制,允许浮点数(float、double、long double)作为非类型模板参数。这让编译期的数学计算和物理量单位系统的设计变得更自然。

cpp
// C++20 之前:不允许
// template<double Factor> double scale(double x) { return x * Factor; }

// C++20:可以了
template<double Factor>
double scale(double x) {
    return x * Factor;
}

auto result = scale<3.14>(10.0);  // 31.4

C++20 前后 NTTP 支持的类型 ​

类型C++17 及之前C++20
整数(int, long 等)支持支持
枚举支持支持
指针/引用支持支持
std::nullptr_t支持支持
浮点数(float, double)不支持支持
字面量类类型不支持支持

基本示例 ​

cpp
#include <iostream>
#include <cmath>
#include <array>
#include <type_traits>

// ============================
// 示例1:浮点数模板参数基本用法
// ============================

template<double Value>
void print_value() {
    std::cout << "模板参数值: " << Value << std::endl;
}

void basic_demo() {
    print_value<3.14>();
    print_value<2.718>();
    print_value<0.0>();
    print_value<-1.5>();
}

// ============================
// 示例2:编译期缩放因子
// ============================

template<double Factor>
double scale(double x) {
    return x * Factor;
}

void scale_demo() {
    // 不同的缩放因子生成不同的函数实例
    std::cout << "scale<2.0>(5.0) = " << scale<2.0>(5.0) << std::endl;     // 10.0
    std::cout << "scale<0.5>(10.0) = " << scale<0.5>(10.0) << std::endl;   // 5.0
    std::cout << "scale<3.14>(1.0) = " << scale<3.14>(1.0) << std::endl;   // 3.14
}

// ============================
// 示例3:编译期数学常量
// ============================

template<double Pi = 3.14159265358979323846>
double circle_area(double radius) {
    return Pi * radius * radius;
}

template<double G = 9.80665>
double free_fall_distance(double time) {
    // s = 0.5 * g * t^2
    return 0.5 * G * time * time;
}

void math_constants_demo() {
    std::cout << "圆面积(r=5): " << circle_area(5.0) << std::endl;
    std::cout << "自由落体(t=3s): " << free_fall_distance(3.0) << " 米" << std::endl;

    // 使用不同的重力加速度(比如月球)
    std::cout << "月球自由落体(t=3s): " << free_fall_distance<1.625>(3.0) << " 米" << std::endl;
}

// ============================
// 示例4:float 类型模板参数
// ============================

template<float Threshold>
bool is_above(float value) {
    return value > Threshold;
}

void float_demo() {
    std::cout << std::boolalpha;
    std::cout << "5.0 > 3.0? " << is_above<3.0f>(5.0f) << std::endl;   // true
    std::cout << "1.0 > 3.0? " << is_above<3.0f>(1.0f) << std::endl;   // false
}

// ============================
// 示例5:编译期线性变换
// ============================

template<double A, double B>
double linear_transform(double x) {
    // y = Ax + B
    return A * x + B;
}

void linear_demo() {
    // y = 2x + 1
    std::cout << "2*3+1 = " << linear_transform<2.0, 1.0>(3.0) << std::endl;  // 7.0

    // y = 0.5x - 3
    std::cout << "0.5*10-3 = " << linear_transform<0.5, -3.0>(10.0) << std::endl;  // 2.0
}

// ============================
// 示例6:constexpr 与 static_assert
// ============================

template<double X>
constexpr double square() {
    return X * X;
}

void constexpr_demo() {
    constexpr double result = square<5.0>();
    static_assert(square<3.0>() == 9.0);  // 编译期验证

    std::cout << "5^2 = " << result << std::endl;
}

// ============================
// 示例7:物理单位的温度转换
// ============================

// 摄氏度转华氏度:F = C * 9/5 + 32
template<double CelsiusOffset = 32.0, double Ratio = 1.8>
double celsius_to_fahrenheit(double celsius) {
    return celsius * Ratio + CelsiusOffset;
}

void temperature_demo() {
    std::cout << "0C = " << celsius_to_fahrenheit(0.0) << "F" << std::endl;     // 32.0
    std::cout << "100C = " << celsius_to_fahrenheit(100.0) << "F" << std::endl; // 212.0
    std::cout << "37C = " << celsius_to_fahrenheit(37.0) << "F" << std::endl;   // 98.6
}

// ============================
// 示例8:auto 推导非类型模板参数
// ============================

template<auto Value>
void print_auto() {
    std::cout << "值: " << Value
              << " 类型: " << typeid(Value).name() << std::endl;
}

void auto_nttp_demo() {
    print_auto<42>();       // int
    print_auto<3.14>();     // double (C++20)
    print_auto<'A'>();      // char
    print_auto<true>();     // bool
}

// ============================
// 示例9:不同浮点值生成不同类型
// ============================

template<double D>
struct FloatTag {
    static constexpr double value = D;
};

void type_identity_demo() {
    // 不同的浮点值产生不同的类型
    FloatTag<1.0> a;
    FloatTag<2.0> b;

    std::cout << std::boolalpha;
    std::cout << "FloatTag<1.0> 和 FloatTag<2.0> 是同类型: "
              << std::is_same_v<decltype(a), decltype(b)> << std::endl;  // false

    FloatTag<1.0> c;
    std::cout << "两个 FloatTag<1.0> 是同类型: "
              << std::is_same_v<decltype(a), decltype(c)> << std::endl;  // true
}

int main() {
    std::cout << "=== 基本用法 ===" << std::endl;
    basic_demo();

    std::cout << "\n=== 缩放 ===" << std::endl;
    scale_demo();

    std::cout << "\n=== 数学常量 ===" << std::endl;
    math_constants_demo();

    std::cout << "\n=== float ===" << std::endl;
    float_demo();

    std::cout << "\n=== 线性变换 ===" << std::endl;
    linear_demo();

    std::cout << "\n=== constexpr ===" << std::endl;
    constexpr_demo();

    std::cout << "\n=== 温度转换 ===" << std::endl;
    temperature_demo();

    std::cout << "\n=== auto NTTP ===" << std::endl;
    auto_nttp_demo();

    std::cout << "\n=== 类型标识 ===" << std::endl;
    type_identity_demo();

    return 0;
}

适用场景 ​

  • 编译期数学常量(圆周率、重力加速度等)
  • 物理单位系统中的转换因子
  • 编译期配置参数(阈值、比例等)
  • DSP/信号处理中的固定系数
  • 编译期线性/仿射变换

常见问题 ​

浮点数的相等比较在模板参数中可靠吗?

模板参数的匹配使用的是编译器内部的浮点表示。template<double D> 中,D 的值在编译期确定,两个相同字面量的浮点值会匹配到同一个模板实例。但要注意,浮点运算的精度问题仍然存在。

可以用浮点 NTTP 做偏特化吗?

可以。和整数 NTTP 一样,浮点 NTTP 也可以用于模板偏特化。

为什么 C++20 之前不允许浮点 NTTP?

主要担忧是浮点数的相等比较问题——不同编译阶段、不同优化级别可能产生微小差异。C++20 解决了这个问题,要求编译器对 NTTP 的浮点值使用确定性的比较。

注意事项 ​

  • 需要 C++20 或更高标准
  • 浮点 NTTP 的值在编译期确定,必须是常量表达式
  • 不同的浮点字面量值生成不同的模板实例
  • NaN 作为 NTTP 值的行为是实现定义的
  • 浮点精度问题仍然存在——避免依赖精确相等

总结 ​

C++20 允许浮点数(float、double、long double)作为非类型模板参数,解除了之前只能用整数类型的限制。这让编译期的数学计算、物理常量传递、配置参数等场景的代码更自然。浮点 NTTP 和整数 NTTP 一样,每个不同的值会生成不同的模板实例。使用时需注意浮点精度问题,避免依赖不同运算路径产生的浮点值精确相等。