Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disallow implicit conversions to int in function call [duplicate]

Tags:

c++

c++11

I have a function:

void foo(int n) {
    std::cout << "foo(int)\n";
}

which can be called using different arguments, it can be char, double, float etc.:

foo(123); // 1
foo('c'); // 2
foo(0.2); // 3
foo(0.2f); // 4
// ...

... but I would like to allow only int arguments (literal or variable), so that 2,3,4,... above would be illegal. My current solution is to delete those overloads with:

void foo(char) = delete;
void foo(float) = delete;
void foo(double) = delete;

but this list of overloads can be really long, and always someone can write a class which will implicitly convert to int what will allow to use my int only function in wrong way, so I found that writing (instead of long explicit list):

template<typename T>
void foo(T) = delete;

works as expected.

Is there any downside to using template as above? or maybe there are some better ways to aprach this problem?

like image 291
mike Avatar asked Jan 11 '17 12:01

mike


1 Answers

You can use static_assert with std::is_same:

template<typename T>
void foo(T i) {
  static_assert(std::is_same<T, int>::value, "Not int");
  std::cout << "foo(int)\n";
}
like image 111
fandyushin Avatar answered Sep 22 '22 01:09

fandyushin