c++ - 显式 int 类型作为参数

标签 c++ type-conversion

是否可以将函数写成:

void func(uint64_t val) {template <typename T>

void call_with(std::function f, T val) { f(val);

int 主要(){ 自动打印 = [](int x) { std::cout << x; }; call_with(打印,42); }}

如果使用 uint64_t 以外的任何其他整数类型调用它,而没有修改我的 #pragma 警告,则会生成编译时错误?

即:

uint32_t x = 0;
func(x) {…} // Error!
func(uint64_t(x)) {…} // Succes!

最佳答案

使用函数模板重载函数。函数模板将更好地匹配除 uint64_t 之外的所有参数类型。您可以定义函数模板,以便在使用时产生错误。

void func(uint64_t val) { ... }

template <typename T>
void func(T)
{
    static_assert(false, "argument type is not uint64_t");
}

对于 C++11,您可以使用以下模板:

template <typename T>
void func(T&&) = delete;

关于c++ - 显式 int 类型作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12958426/

相关文章:

c++ - 对齐的 malloc C++ 实现

c++ - 如何在构造函数上指定不可推导的模板参数?

f# - 小数与整数相乘 F#

c++ - 将 C 代码移植到 C++,将 void* 从 malloc 转换为所需指针的问题

c - C中什么时候发生类型转换

xcode - 归档时 Xcode 中的几个打字问题

javascript - 字符串的余数/模数是一个数字

c++ - 包含目录中的所有文件?

c# - 如何解决 Windows Certificate app Supported "API test"test result fail

c++ - 竞争条件仿真在 xcode 中崩溃