停止函数隐式转换
今天我遇到了一个奇怪的情况,我需要一个函数来不隐式转换值。
经过一番谷歌搜索后,我发现了这个 http://www.devx.com/cplus/10MinuteSolution/37078/1954< /a>
但我认为对我想要阻止的所有其他类型使用函数重载有点愚蠢,所以我这样做了。
void function(int& ints_only_please){}
int main()
{
字符a=0;
整数b=0;
函数(a);
函数(b);
}
我向朋友展示了代码,他建议我在 int 之前添加 const ,这样变量就不可编辑,但是当我开始编译时,编译得很好,但不应该,请看下面,看看我的意思
void function(const int& ints_only_please){}
int main()
{
字符a=0;
整数b=0;
函数(a); //编译器应该停在这里,但 const int 却不会
函数(b);
}
有谁知道这是为什么?
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?
使用模板来获得所需的效果:
请注意,我们只为
int
编写了特殊版本的模板,因此使用任何其他类型作为模板参数的调用都会导致编译错误。Use templates to get the desired effect:
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.