是否可以将函数写成:
void func(uint64_t val) {template <typename T>
void call_with(std::function
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/