gpt4 book ai didi

c++ - 停止函数隐式转换

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:43 27 4
gpt4 key购买 nike

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

在谷歌上搜索后,我找到了这个 http://www.devx.com/cplus/10MinuteSolution/37078/1954

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


void function(int& ints_only_please){}<p></p>

<p>int main()
{
char a=0;
int b=0;
function(a);
function(b);
}
</p>

我把代码给一个 friend 看,他建议我在 int 之前添加 const,这样变量就不可编辑了,但是当我开始编译时很好,但它不应该,请看下面看看我的意思


void function(const int& ints_only_please){}<p></p>

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

谁知道这是为什么?

最佳答案

使用模板获得想要的效果:

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 编写了一个特殊版本的模板,因此将任何其他类型作为模板参数的调用将导致编译错误。

关于c++ - 停止函数隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4603717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com