-1

I don't want my code to compile or handle invalid input / argument. In this case, it should only accept int variables and nothing else.

#include <iostream>
class calc{
public:
    int add2(int x){
       return x + 2;
    }
};

// Inside testing file    
int main(){
calc c;
// Should not output anything / throw error since argument is 'a' and not a integer 
 std::cout<<c.add2('a'); // But it outputs 99. 
}

I understand c++ is doing its implicit conversion here but I don't know how to stop it from happening. Or is there a way to check if the input passed is of int type and nothing else?

  • You could add `int add2(char) = delete;` , I suppose. – WhozCraig May 22 '21 at 12:47
  • I want to handle bool , float, and any other data types that would convert to int implicitly. So I was wondering if there is a universal way to do it and not just for chat. Basically I want to handle all invalid input – Prateek Arora May 22 '21 at 12:52
  • 1
    I have no idea what that means, but if you want to explicitly *error* on explicitly *char* what I showed would do it. If you want to compile-time-error on everything but truly `int` you could always use sfinae and `template std::enable_if_t::value, int> add2(T x)` – WhozCraig May 22 '21 at 12:53
  • @PrateekArora I don't fully understand. What is "invalid input"? Do you want to allow implicit conversion for some types, or prohibit it for all types except `int`? – flowit May 22 '21 at 12:54
  • 3
    Does this answer your question? [How do I avoid implicit conversions on non-constructing functions?](https://stackoverflow.com/questions/12877546/how-do-i-avoid-implicit-conversions-on-non-constructing-functions) – flowit May 22 '21 at 12:56
  • @PrateekArora, the point is that `char` _is_ convertible to `int`. – Enlico May 22 '21 at 13:01

1 Answers1

1

The point is that char is convertible to int, so what you wrote in a comment

I want to handle bool , float, and any other data types that would convert to int implicitly

is already true for your code. So you probably want to just prevent the conversion to char. If that's the case, you can template the function and static_assert inside it that T be convertible to int but it's not char:

#include <iostream>
#include <type_traits>
class calc {
public:
    template<typename T>
    T add2(T x) {
        static_assert(std::is_convertible_v<T, int> && !std::is_same_v<T, char>);
        return x + 2;
    }
};

int main() {
    calc c;

    //std::cout << c.add2('a'); // fails
    std::cout << c.add2(1); // works
    std::cout << c.add2(1.5); // works
    std::cout << c.add2(1.5f); // works
    std::cout << c.add2(15ll); // works
}
Enlico
  • 23,259
  • 6
  • 48
  • 102