非类型模板参数字面量类类型支持 ​

什么是字面量类类型 NTTP ​

C++20 允许字面量类类型(literal class type)作为非类型模板参数(NTTP)。在此之前,模板参数只能是整数、枚举、指针等简单类型。现在你可以把一个自定义的结构体实例直接传给模板。

要作为 NTTP 使用,类类型必须是"结构化类型"(structural type),需要满足以下条件:

  • 所有基类和非静态数据成员都是 public 的且非 mutable
  • 所有基类和非静态数据成员的类型本身也是结构化类型
  • 类型是字面量类型(有 constexpr 构造函数)
cpp
struct Point {
    int x, y;  // 公有、非 mutable
};

template<Point P>
void print_point() {
    std::cout << "(" << P.x << ", " << P.y << ")" << std::endl;
}

print_point<Point{3, 4}>();  // (3, 4)

结构化类型的要求 ​

要求说明
所有数据成员 public不能有 private 或 protected 数据成员
非 mutable 成员数据成员不能标记 mutable
成员类型是结构化类型int、double、枚举、其他结构化类等
字面量类型需要 constexpr 构造函数
无虚函数不能有虚函数或虚基类

基本示例 ​

cpp
#include <iostream>
#include <array>
#include <string_view>
#include <type_traits>
#include <algorithm>

// ============================
// 示例1:简单结构体作为 NTTP
// ============================

struct Color {
    int r, g, b;
};

template<Color C>
void print_color() {
    std::cout << "RGB(" << C.r << ", " << C.g << ", " << C.b << ")" << std::endl;
}

void basic_demo() {
    print_color<Color{255, 0, 0}>();    // RGB(255, 0, 0)
    print_color<Color{0, 128, 255}>();  // RGB(0, 128, 255)

    // 也可以用 constexpr 变量
    constexpr Color green{0, 255, 0};
    print_color<green>();               // RGB(0, 255, 0)
}

// ============================
// 示例2:编译期字符串(固定长度)
// ============================

template<std::size_t N>
struct FixedString {
    char data[N]{};

    // constexpr 构造函数,从字符数组初始化
    constexpr FixedString(const char (&str)[N]) {
        for (std::size_t i = 0; i < N; i++) {
            data[i] = str[i];
        }
    }

    // 转为 string_view
    constexpr std::string_view view() const {
        return {data, N - 1};  // 去掉末尾 '\0'
    }
};

// 推导指引:从字面量推导 N
template<std::size_t N>
FixedString(const char (&)[N]) -> FixedString<N>;

template<FixedString Str>
void print_fixed_string() {
    std::cout << "字符串: " << Str.view() << std::endl;
}

void string_demo() {
    print_fixed_string<"Hello">();
    print_fixed_string<"C++20">();
    print_fixed_string<"Template">();
}

// ============================
// 示例3:编译期配置
// ============================

struct Config {
    int width;
    int height;
    bool fullscreen;
    double scale;
};

template<Config Cfg>
class Window {
public:
    void info() const {
        std::cout << "窗口: " << Cfg.width << "x" << Cfg.height;
        if (Cfg.fullscreen) std::cout << " (全屏)";
        std::cout << " 缩放: " << Cfg.scale << std::endl;
    }

    // 编译期条件编译
    void render() const {
        if constexpr (Cfg.fullscreen) {
            std::cout << "  全屏渲染模式" << std::endl;
        } else {
            std::cout << "  窗口渲染模式" << std::endl;
        }
    }
};

void config_demo() {
    constexpr Config cfg1{1920, 1080, true, 1.0};
    constexpr Config cfg2{800, 600, false, 2.0};

    Window<cfg1> w1;
    Window<cfg2> w2;

    w1.info();
    w1.render();
    w2.info();
    w2.render();
}

// ============================
// 示例4:if constexpr 分支消除
// ============================

struct OptionalInt {
    bool has_value;
    int value;

    constexpr OptionalInt() : has_value(false), value(0) {}
    constexpr OptionalInt(int v) : has_value(true), value(v) {}
};

template<OptionalInt Opt>
void process() {
    // 编译期根据是否有值选择不同分支
    if constexpr (Opt.has_value) {
        std::cout << "有值: " << Opt.value << std::endl;
    } else {
        std::cout << "无值" << std::endl;
    }
}

void optional_demo() {
    process<OptionalInt{42}>();    // 有值: 42
    process<OptionalInt{}>();      // 无值
    process<OptionalInt{100}>();   // 有值: 100
}

// ============================
// 示例5:std::array 和 std::pair 作为 NTTP
// ============================

// std::array 满足结构化类型要求
template<std::array<int, 3> Arr>
void print_array() {
    std::cout << "[";
    for (std::size_t i = 0; i < Arr.size(); i++) {
        if (i > 0) std::cout << ", ";
        std::cout << Arr[i];
    }
    std::cout << "]" << std::endl;
}

// std::pair 也可以(前提是元素类型是结构化类型)
template<std::pair<int, int> P>
void print_pair() {
    std::cout << "(" << P.first << ", " << P.second << ")" << std::endl;
}

void stl_demo() {
    print_array<std::array<int, 3>{1, 2, 3}>();
    print_array<std::array<int, 3>{10, 20, 30}>();

    print_pair<std::pair<int, int>{42, 99}>();
}

// ============================
// 示例6:嵌套结构体
// ============================

struct Vector2D {
    double x, y;
};

struct Rect {
    Vector2D origin;
    Vector2D size;
};

template<Rect R>
void describe_rect() {
    std::cout << "矩形: 原点(" << R.origin.x << ", " << R.origin.y
              << ") 大小(" << R.size.x << "x" << R.size.y << ")"
              << std::endl;
}

void nested_demo() {
    constexpr Rect r1{{0.0, 0.0}, {100.0, 50.0}};
    constexpr Rect r2{{10.5, 20.3}, {200.0, 100.0}};

    describe_rect<r1>();
    describe_rect<r2>();
}

// ============================
// 示例7:不满足条件的类型——编译错误
// ============================

/*
// 以下类型不能作为 NTTP:

// 1. 有 private 成员
struct Bad1 {
    int x;
private:
    int y;  // private 成员不行
};

// 2. 有 mutable 成员
struct Bad2 {
    mutable int x;  // mutable 不行
};

// 3. std::string(不是字面量类型)
// template<std::string S> void foo();  // 编译错误

// 4. std::optional(有 private 成员)
// template<std::optional<int> O> void bar();  // 编译错误
*/

int main() {
    std::cout << "=== 基本结构体 ===" << std::endl;
    basic_demo();

    std::cout << "\n=== 编译期字符串 ===" << std::endl;
    string_demo();

    std::cout << "\n=== 编译期配置 ===" << std::endl;
    config_demo();

    std::cout << "\n=== OptionalInt ===" << std::endl;
    optional_demo();

    std::cout << "\n=== STL 类型 ===" << std::endl;
    stl_demo();

    std::cout << "\n=== 嵌套结构体 ===" << std::endl;
    nested_demo();

    return 0;
}

可以作为 NTTP 的标准库类型 ​

类型可以作为 NTTP原因
std::array<T, N>可以(T 是结构化类型时)公有成员
std::pair<T, U>可以(T、U 是结构化类型时)公有成员
std::optional<T>不行(C++20)有 private 成员
std::string不行非字面量类型
std::vector<T>不行非字面量类型
std::tuple<T...>不行(C++20)有 private 成员

适用场景 ​

  • 编译期配置参数(窗口大小、渲染选项等)
  • 编译期字符串(固定长度字符串作为模板参数)
  • 编译期几何/数学对象(点、矩形、向量等)
  • 有条件的编译期分支消除(if constexpr + 结构体字段)
  • 标签分发和类型区分

常见问题 ​

为什么数据成员必须是 public 的?

因为编译器需要比较两个 NTTP 值是否相等,比较是按成员逐一进行的。如果有 private 成员,编译器无法在模板参数匹配时访问它们。

std::string 为什么不能作为 NTTP?

std::string 不是字面量类型,它的内部存储涉及动态内存分配。可以用固定长度的字符数组包装(如上面的 FixedString)来替代。

两个值相同的 NTTP 会共享同一个模板实例吗?

是的。编译器通过按成员逐一比较来判断两个 NTTP 值是否相等,相等则使用同一个模板实例。

注意事项 ​

  • 需要 C++20 或更高标准
  • 类类型必须满足结构化类型的所有要求
  • 所有数据成员必须 public、非 mutable
  • std::string、std::vector 等涉及动态分配的类型不能使用
  • 不同编译器的支持程度可能不同——GCC 最早支持

总结 ​

C++20 允许字面量类类型作为非类型模板参数,前提是该类型满足"结构化类型"的要求:所有数据成员 public、非 mutable,且成员类型本身也是结构化类型。这让自定义结构体(如配置、坐标、颜色等)可以直接传递给模板,在编译期使用 if constexpr 做分支消除。标准库中 std::array 和 std::pair 可以作为 NTTP,但 std::string、std::optional 等因为有 private 成员或非字面量类型而不行。