Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;-如何处理/避免将char到int隐式转换为函数参数_C++_Implicit Conversion - Fatal编程技术网

C++ C++;-如何处理/避免将char到int隐式转换为函数参数

C++ C++;-如何处理/避免将char到int隐式转换为函数参数,c++,implicit-conversion,C++,Implicit Conversion,我不希望我的代码编译或处理无效的输入/参数。在这种情况下,它应该只接受int变量,而不接受其他变量 #include <iostream> class calc{ public: int add2(int x){ return x + 2; } }; // Inside testing file int main(){ calc c; // Should not output anything / throw error since argum

我不希望我的代码编译或处理无效的输入/参数。在这种情况下,它应该只接受int变量,而不接受其他变量

#include <iostream>
class calc{
public:
    int add2(int x){
       return x + 2;
    }
};

// Inside testing file    
int main(){
calc c;
// Should not output anything / throw error since argument is 'a' and not a integer 
 std::cout<<c.add2('a'); // But it outputs 99. 
}
#包括
类计算{
公众:
内部地址2(内部地址x){
返回x+2;
}
};
//内部测试文件
int main(){
钙;
//不应输出任何内容/抛出错误,因为参数是“a”而不是整数

std::cout重点是
char
可以转换为
int
,因此您在注释中所写的


我想处理bool、float和任何其他隐式转换为int的数据类型

对于您的代码来说已经是如此。因此您可能只想阻止转换为
char
。如果是这种情况,您可以对函数进行模板化,并在其内部声明
T
可转换为
int
,但它不是
char

#包括
#包括
类计算{
公众:
样板
T地址2(T x){
静态断言(std::is_convertible_v&&!std::is_same_v);
返回x+2;
}
};
int main(){
钙;

//std::您可以添加
intadd2(char)吗=delete;
,我想。我想处理bool、float和任何其他隐式转换为int的数据类型。所以我想知道是否有一种通用的方法来实现这一点,而不仅仅是为了聊天。基本上,我想处理所有无效的input。我不知道这意味着什么,但如果你想显式地在显式char上出错,我显示了w我会的。如果你想编译所有东西的时间错误,但真正的
int
,你可以使用sfinae和
模板std::enable\u If\u t add2(tx)
@PrateekArora,我不完全理解。什么是“无效输入”?是否允许对某些类型进行隐式转换,或禁止对除
int
以外的所有类型进行隐式转换?这是否回答了您的问题?