停止函数隐式转换 [英] Stopping function implicit conversion
问题描述
我遇到了一个奇怪的情况,今天我需要一个函数来不隐式转换值。
I came across a strange situation today where I needed a function to not implicitly convert values.
在google上查找后,我发现这个 http://www.devx.com/cplus/10MinuteSolution/37078/1954
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);
}
int main() { char a=0; int b=0; function(a); function(b); }
我向朋友展示了代码, const before int所以变量不可编辑,但是当我开始编译好但不应该,看看下面看看我的意思
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); //编译器应该停在这里,但它不与const int
function(b);
}
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?
推荐答案
使用模板获得所需效果:
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;
}
注意,我们只写一个特殊版本的模板 int
,以便具有任何其他类型作为模板参数的调用将导致编译错误。
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屋!