开发者

Stopping function implicit conversion

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 wit开发者_如何学编程h const int function(b); }

Does anyone know why this is?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜