How to prevent floating-point being implicitly converted to integral value at function call?
#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;
}
Here the outputs are 2 and 3 respectively.
I am compiling with g++ -std=c++11 31014.cpp -o 31014 -v. And there is no mention of 3.5 being converted to 3.
Is there a way to prevent, or atleast detect, this?
Kindly help me out, please.
There are multiple ways to handle this in c++11.
Method 1: You SFINAE the function template fn by using std::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;
}
Demo
Method 2: Alternatively, delete the functions using =delete, which shouldn't take place in
template deduction.
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
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With