gpt4 book ai didi

c++ - 参数类型为 'const C s[N]' 的模板函数(C 类型元素的固定大小数组)

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:17 24 4
gpt4 key购买 nike

如何编译下面的代码?

    template <typename C, size_t N>
constexpr uint64_t cs_hash(const C s[N])
{
return N;
}

constexpr char sample[] = "communism";

constexpr uint64_t h = cs_hash(sample);

MSVC 2017 的编译器错误是

error C2784: 'uint64_t cs_hash(const C [N])': could not deduce template argument for 'const C [N]' from 'const char [10]'

最佳答案

使用const 引用!

template <typename C, size_t N>
constexpr uint64_t cs_hash(const C (&s)[N])
{
return N;
}

解释

当您尝试创建类型为 T []T [N] 的函数参数时,编译器会自动将类型替换为 T *.

这意味着你的函数声明与

template <typename C, size_t N>
constexpr uint64_t cs_hash(const C *s)
{
return N;
}

由于参数类型不依赖于N,因此无法推导出N

但是当您使用“对数组的引用”参数时,上述数组参数规则不适用,并且没有什么能阻止推导正常工作。

关于c++ - 参数类型为 'const C s[N]' 的模板函数(C 类型元素的固定大小数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52244322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com