简体   繁体   English

将参数隐式转换为布尔

[英]Implicitly cast parameter to bool

Premise: I am trying to make a Define scope that is not implemented using a macro because of the potential issues with macros. 前提:由于宏的潜在问题,我试图创建一个未使用宏实现的定义范围。 Here is my initial attempt 这是我最初的尝试

//version for if not defined
bool Defined()
{
    return false
}

//version for if defined
bool Defined(bool anything)
{
    return true;
}

And an example use case 还有一个用例示例

if(Defined(_DEBUG))
{
    Stuff...
}

which would replace 它将取代

#ifdef _DEBUG
    Stuff...
#endif

or 要么

#define Defined()         false
#define Defined(Anything) true

Benefits: 优点:
syntax is cleaner, it is scoped, 语法更清晰,范围更广,

This code is not conditional, so the compiler will be able to easily optimize code sections out. 该代码不是有条件的,因此编译器将能够轻松地优化代码段。

Issues 问题
There are a few issues with this procedure, the first is the reason for this post. 此过程存在一些问题,第一个是发布此帖子的原因。

Question: 题:
You can't pass in anything that is not implicitly cast-able to a bool. 您不能传递任何无法隐式转换为布尔值的内容。 Is there a way to implicitly cast any object, number, pointer, etc to a bool? 有没有一种方法可以将任何对象,数字,指针等隐式转换为布尔值? I don't believe there is, but I wanted to make sure, before I continued. 我不相信那里,但是我想确定一下,然后再继续。

You can use a generic template: 您可以使用通用模板:

template<class T>
bool Defined(T &&) { return true; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM