我在C++中使用以下示例程序
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
namespace mine{
template<class T>
inline void swap(T &a, T &b){
char c= a; //This should not have compiled
a=b;
b=c;
}
}
int main(){
int a,b;
cout<< "Enter two values: ";
cin>>a>>b;
mine::swap(a,b); //type variable T is instantiated as in
cout << a <<' '<<b << endl;
}
Run Code Online (Sandbox Code Playgroud)
我期待编译器在swap函数中抛出一个错误,因为c被声明为char,但是分配了泛型类型变量T的变量.不仅如此,在调用swap时,T被实例化为int.但是,不仅g ++没有给出任何错误,程序也能完美运行.为什么会这样?
C++让你有能力用脚射击自己.
事实上,任何整数类型都可以转换为char具有实现定义行为的类型.
编译器假设你知道你在做什么,就是这样.
auto c = a;这些天是最好的替代品.在C++ 11之前你可以编写T C = a;(当然你仍然可以.)虽然从std::move交换时你应该使用C++ 11 ,看看std::swap你的平台是如何实现的.(参考标准库如何实现std :: swap?)
如果-Wconversion在命令行中指定,gcc将警告您.