gpt4 book ai didi

c++ - 有没有办法消除这种歧义?

转载 作者:行者123 更新时间:2023-11-27 22:34:53 28 4
gpt4 key购买 nike

我想提供两种形式的 GetLength(psz) 样式函数 - 一种不知道上限,另一种知道:

template <typename T>
size_t GetLength(const T * psz) { /* compute size w/o knowing what upper bound may be */ }

template <typename T, size_t size>
size_t GetLength(const T(&psz)[size]) { /* we know the upper bound */ }

我希望这不会模棱两可。当参数是已知大小的数组时,我希望选择数组大小的版本。当参数只是一个指针而不是已知的固定数组时,我希望选择无界版本。

我还提供了第三个版本,它明确地将上限作为参数,没有模板化大小扣除,用于从外部上下文传递该信息,否则该外部上下文将失去从其本地参数推断出该信息的能力。

有没有一种技术可以用来强制编译器在边界已知时打折函数的第一个版本(未知边界)?

最佳答案

Is there a technique I can use to force the compiler to discount the 1st version of my function (no known bounds) when the bounds is known?

添加一个间接级别怎么样?

template <typename T>
std::size_t GetLength (const T * psz, int)
{ /* compute size w/o knowing what upper bound may be */ }

template <typename T, size_t size>
std::size_t GetLength (const T(&psz)[size], long)
{ /* we know the upper bound */ }

template <typename T>
std::size_t GetLength (T const & t)
{ GetLength(t, 0L); }

添加一个未使用的不同参数(intlong)您可以选择首选版本。

关于c++ - 有没有办法消除这种歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049232/

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