Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent floating-point being implicitly converted to integral value at function call in c++? [duplicate]

Tags:

c++

gcc

c++11

g++

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.

like image 304
Supreeto Avatar asked Oct 20 '25 04:10

Supreeto


1 Answers

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

like image 149
Anoop Rana Avatar answered Oct 22 '25 16:10

Anoop Rana