简体   繁体   English

需要一些帮助来编写EMPTY_OR宏

[英]Need some help writing an EMPTY_OR macro

I'm trying to code a macro called EMPTY_OR , which will return the first argument, but if it's empty, it will return the second one. 我正在尝试编写一个名为EMPTY_OR的宏,该宏将返回第一个参数,但如果为空,则将返回第二个参数。

Here's what I have so far: 这是我到目前为止的内容:

#include <iostream>

#define EMPTY_OR(x, y) ( (sizeof(#x) > sizeof("")) ? (x) : (y) )

#define TEST(x, y) EMPTY_OR(y, x)

using namespace std;

int main()
{
    int four = TEST(4, );
    int eight = TEST(4, 8);
    cout << "four: " << four << endl;
    cout << "eight: " << eight << endl;
    return 0;
}

It's close, but it doesn't work because the first line of the main function expands to the following: 它已经关闭,但是由于main功能的第一行扩展为以下内容,因此无法使用:

( (sizeof("") > sizeof("")) ? () : (4) )

The condition is never true, so () is never evaluated. 条件永远不会为真,因此()永远不会被求值。 I shouldn't care about it, but the compiler does, and it shows an error. 我不在乎,但编译器会在意,并且显示错误。

How can I solve it with the most straightforward and standard-compliant (or at least MSVC-compliant) way? 我该如何以最直接,最符合标准(或至少符合MSVC)的方式解决问题?

如果我了解您要正确执行的操作,请删除sizeof,然后检查字符串中的第一个字符是否为\\0

#define EMPTY_OR(x, y) ( #x[0] ? (x+0) : (y) )

Here's a solution adapted from this article and without Boost that works on anything that I can think of that you can pass: 这是从本文改编的解决方案,没有Boost可以解决我认为可以通过的任何问题:

#define CAT(a, b) CAT_(a, b)
#define CAT_(a, b) a##b

#define IF(cond, t, f) CAT(IF_, cond)(t, f)
#define IF_1(t, f) t
#define IF_0(t, f) f

#define COMMA(x) ,

#define ARG3(a, b, c, ...) c
#define HAS_COMMA(x) ARG3(x, 1, 0,)

#define EMPTY(x) EMPTY_(HAS_COMMA(COMMA x ()))

#define EMPTY_(x) HAS_COMMA(CAT(EMPTY_, x))
#define EMPTY_1 ,

#define EMPTY_OR(x, y) IF(EMPTY(x), y, x)
#define TEST(x, y) EMPTY_OR(y, x)


#include <iostream>
using namespace std;

int main()
{
    int t = TEST(1==, ) 1;
    int f = TEST(1==, 0==) 1;
    cout << "t: " << t << endl;
    cout << "f: " << f << endl;
    return 0;
}

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

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