Question

I came across a strange situation today where I needed a function to not implicitly convert values.

After some looking on google I found this http://www.devx.com/cplus/10MinuteSolution/37078/1954

But I thought it was a bit stupid to use a function overload for every other type I want to block so instead I did this.


void function(int& ints_only_please){}

int main() { char a=0; int b=0; function(a); function(b); }

I showed the code to a friend and he suggested I added const before int so the variable isn't editable, however when I did started compiling fine but it shouldn't, look below to see what I mean


void function(const int& ints_only_please){}

int main() { char a=0; int b=0; function(a); //Compiler should stop here but it doesn't with const int function(b); }

Does anyone know why this is?

Was it helpful?

Solution

Use templates to get the desired effect:

template <class T>
void foo(const T& t);

template <>
void foo<int>(const int& t)
{

}

int main(){
  foo(9); // will compile
  foo(9.0); // will not compile
  return 0;
}

Note that we only write a special version of the template for int so that a call that has any other type as a template parameter will result in a compile error.

OTHER TIPS

It is legal to bind a temporary to a const reference, but not a non-const reference.

A char can be implicitly converted to an int and the temporary that is the result of this conversion can be bound to a const int& function parameter extending the temporary's lifetime until the function exits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top