如何避免对非构造函数进行隐式转换? [英] How do I avoid implicit conversions on non-constructing functions?

查看:186
本文介绍了如何避免对非构造函数进行隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何避免在非构造函数上进行隐式转换?

我有一个函数将一个整数作为参数,

但该函数也将转换为字符,bools ,和longs。

我相信这是通过隐式地转换它们。

如何避免这种情况,以便该函数只接受匹配类型的参数,并拒绝编译否则?

有一个关键字explicit,但它不适用于非构造函数。 :\


我该怎么办?



下面的程序会编译,尽管我不想这样做:

  #include< cstdlib> 

//函数签名需要一个int
void函数(int i);

int main(){

int i {5};
函数(i); //< - 这是可接受的

char c {'a'};
函数(c); //< - 我不想这样编译

return EXIT_SUCCESS;


void function(int i){return;}



<请务必指出任何滥用术语和假设的情况。 您不能直接,因为 char 自动被提升为 int

你可以使用一个技巧:创建一个以 char 作为参数的函数,但不要实现它。它会编译,但你会得到一个链接器错误:

pre $ void函数(int i)
{
}
void function(char i);
//或者,在C ++中11
void function(char i)= delete;

使用 char 参数调用函数将会打破构建。



请参阅 http://ideone.com/ 2SRdM



术语:非构造函数?你的意思是一个不是构造函数的函数吗?


How do I avoid implicit casting on non-constructing functions?
I have a function that takes an integer as a parameter,
but that function will also take characters, bools, and longs.
I believe it does this by implicitly casting them.
How can I avoid this so that the function only accepts parameters of a matching type, and will refuse to compile otherwise?
There is a keyword "explicit" but it does not work on non-constructing functions. :\
what do I do?

The following program compiles, although I'd like it not to:

#include <cstdlib>

//the function signature requires an int
void function(int i);

int main(){

    int i{5};
    function(i); //<- this is acceptable

    char c{'a'};
    function(c); //<- I would NOT like this to compile

    return EXIT_SUCCESS;
}

void function(int i){return;}

*please be sure to point out any misuse of terminology and assumptions

解决方案

You can't directly, because a char automatically gets promoted to int.

You can resort to a trick though: create a function that takes a char as parameter and don't implement it. It will compile, but you'll get a linker error:

void function(int i) 
{
}
void function(char i);
//or, in C++11
void function(char i) = delete;

Calling the function with a char parameter will break the build.

See http://ideone.com/2SRdM

Terminology: non-construcing functions? Do you mean a function that is not a constructor?

这篇关于如何避免对非构造函数进行隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆