You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++17中如何以数组引用为模板参数用花括号初始化类对象

正确实现方式

你的代码核心问题在于类模板实例化时未让编译器推导模板参数,以及未处理成员数组的初始化。以下是适配普通数组和宽字符串字面量(如L"test")的正确实现:

关键点说明

  • 利用C++17的类模板参数推导(CTAD),编译器可从传入的数组自动推导T(元素类型)和ar_sz(数组大小);
  • 构造函数接收数组的左值引用,完美匹配普通数组与字符串字面量的类型;
  • 若需兼容C++17之前版本,需显式指定模板参数。

完整代码

#include <algorithm>
#include <type_traits>
#include <cstdio>

template<typename T, size_t ar_sz> 
class Test_class {
    T array[ar_sz];
public:
    // 接收数组引用的构造函数,支持参数推导
    Test_class(const T (&input_array)[ar_sz]) {
        // 将传入数组的内容复制到成员数组
        std::copy(std::begin(input_array), std::end(input_array), std::begin(array));
    }

    // 验证用的打印方法
    void print() const {
        for (size_t i = 0; i < ar_sz; ++i) {
            if constexpr (std::is_same_v<T, wchar_t>) {
                wprintf(L"%c", array[i]);
            } else {
                printf("%d ", array[i]);
            }
        }
        printf("\n");
    }
};

int main() {
    // 测试普通int数组
    constexpr size_t array_sz = 1;
    int ar_i[array_sz]{ 1 };
    Test_class test_ar{ ar_i }; // C++17+自动推导模板参数
    test_ar.print();

    // 测试宽字符串字面量L"test"(类型为const wchar_t[5])
    Test_class test_str{ L"test" };
    test_str.print();
}

兼容C++17之前版本的写法

如果编译器不支持C++17,实例化时必须显式指定模板参数:

// 普通数组实例化
Test_class<int, array_sz> test_ar{ ar_i };
// 宽字符串实例化
Test_class<const wchar_t, 5> test_str{ L"test" };

内容的提问来源于stack exchange,提问作者hgrev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:12:55