mercredi 15 juillet 2020

Prevent implicit conversion for primary data types C++

BLOT: C++ has implicit conversion, I am looking for a way to prevent it.

Let me take an example for the same, for the code snippet below:

#include <iostream>

int incrementByOne(int i) {
    return ++i;
}

int main()
{
    bool b = true;
    
    std::cout << incrementByOne(b) << std::endl;

    return 0;
}

It would output: 2

How can I prevent such implicit conversions and be strict about taking only int as an argument even at runtime?

One way I can think of is overload the function. So the new code would look like:

#include <iostream>

int incrementByOne(int i) {
    return ++i;
}

int incrementByOne(bool) {
    std::cerr << "Please provide integer as argument" << std::endl;
    exit(0);
}

int incrementByOne(char) {
    std::cerr << "Please provide integer as argument" << std::endl;
    exit(0);
}

int main()
{
    bool b = true;
    
    std::cout << incrementByOne(b) << std::endl;

    return 0;
}

Is there any other(recommended) way of preventing implicit conversions at runtime?

Aucun commentaire:

Enregistrer un commentaire