gpt4 book ai didi

c++ - 防止将 uint64_t 转换为 uint16_t

转载 作者:IT老高 更新时间:2023-10-28 22:31:29 26 4
gpt4 key购买 nike

为什么下面的代码在clang++中编译?

是否有任何 c++ 标志来防止这种情况发生 - 我希望编译器抛出错误,因为我将 std::uint64_t 作为参数传递给接受 std::uint16_t 的函数。

#include <cstdint>
using namespace std;

void foo(uint16_t x) {
}

int main() {
uint64_t x = 10000;
foo(x);
return 0;
}

最佳答案

你可以在 c++11 中删除一个函数

void foo(uint64_t) = delete;

它通过在函数重载解析时添加签名来工作,如果匹配得更好,则会发生错误。您也可以使其通用,只允许您的原始签名

template <class T> void foo( T&& ) = delete;

关于c++ - 防止将 uint64_t 转换为 uint16_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30583090/

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