如何防止浮点数在函数调用时隐式转换为整数值?
#include <iostream>
void fn(int x) {
std::cout<<"fn("<<x<<")\n";
}
int main() {
std::cout<<"Hello, this is 301014 :)\n";
fn(2);
fn(3.5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里的输出分别是2和3。
我正在编译g++ -std=c++11 31014.cpp -o 31014 -v。并且没有提到3.5转换为3。
有没有办法防止或至少检测到这种情况?
请帮帮我。
在c++11中有多种方法可以处理这个问题。
方法 1:通过使用SFINAE函数模板。fnstd::enable_if
template<typename T>
typename std::enable_if<std::is_same<T, int>::value>::type fn(T x) {
std::cout << "fn(" << x << ")\n";
}
int main() {
std::cout << "Hello, this is 301014 :)\n";
fn(2); // works
// fn(3.5); // won't work;
}
Run Code Online (Sandbox Code Playgroud)
方法二:或者,删除使用 的函数=delete,模板推导中不应出现该函数。
void fn(int x) { // #1
std::cout << "fn(" << x << ")\n";
}
template<typename T> void fn(T) = delete; // #2
int main() {
std::cout << "Hello, this is 301014 :)\n";
fn(2); // works using #1
// fn(3.5); // won't work since it uses #2
}
Run Code Online (Sandbox Code Playgroud)
解决此问题的另一种方法是添加template<typename T> void fn(T)=delete;(也适用于较旧的 C++ 标准):
#include <iostream>
template<typename T> void fn(T)=delete;
void fn(int x) {
std::cout<<"fn("<<x<<")\n";
}
int main() {
std::cout<<"Hello, this is 301014 :)\n";
fn(2);
fn(3.5); // now gives error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |