gpt4 book ai didi

没有任意参数的c++函数模板

转载 作者:太空宇宙 更新时间:2023-11-04 14:54:29 26 4
gpt4 key购买 nike

考虑这个工作正常的 c++ 代码:

template <size_t N>
int check(std::array<unsigned char, N> buf){
std::cout << N << "-" << buf.size() << std::endl;
return 0;
}


int main (int argc, char *argv[])
{
std::array<unsigned char, 20> a;
std::array<unsigned char, 30> b;
std::array<unsigned char, 40> c;

check(a);
check(b);
check(c);

return 0;
}

是否可以显式实例化 N=20 和 N=30 的“检查”,但禁用任何其他隐式实例化?

这意味着如果我使用“check(c)”,我想得到一个编译时错误,

编辑:

事实上,我想要相同的实现,所以模板是正确的选择,如果出于某种原因我用不应该存在的参数实例化它,我只想出现编译时错误。正因为如此,static_assert (c++11) 解决方案看起来是最好的,因为它完整地解决了问题并且非常易于阅读。

最佳答案

如果 N 不是 20 或 30,您可以使用 static_assert 抛出编译时错误。

template <size_t N>
int check(std::array<unsigned char, N> buf)
{
static_assert(N == 20 || N == 30, "N must be 20 or 30.");

std::cout << N << "-" << buf.size() << std::endl;

return 0;
}

关于没有任意参数的c++函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209654/

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