停止函数隐式转换

Gen*_*rhc 5 c++ mingw function implicit-conversion

我今天遇到了一个奇怪的情况,我需要一个不隐式转换值的函数.

经过一些谷歌搜索后,我发现了这个http://www.devx.com/cplus/10MinuteSolution/37078/1954

但我认为对我想要阻止的其他类型使用函数重载有点愚蠢,所以我做了这个.


void function(int& ints_only_please){}

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

我向朋友展示了代码,他建议我在int之前添加const,这样变量就不可编辑了,但是当我开始编译时很好但不应该这样,看下面看看我的意思


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); }

有人知道为什么吗?

小智 14

使用模板获得所需的效果:

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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们只编写模板的特殊版本,int以便具有任何其他类型作为模板参数的调用将导致编译错误.

  • 不要忘记,`signed int`(或`int`)!=`unsigned int`.你需要*each*type一个函数. (2认同)

CB *_*ley 7

将临时绑定到const引用是合法的,但不是非const引用.

A char可以隐式转换为a,int并且作为此转换结果的临时值可以绑定到const int&延长临时生命周期的函数参数,直到函数退出.