有没有一种方法可以在不创建变量的情况下调用需要指针的函数? [英] Is there a way to call a function expecting a pointer without creating variable?

查看:82
本文介绍了有没有一种方法可以在不创建变量的情况下调用需要指针的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数调用:

uint32_t func(uint32_t* a, uint32_t b)

我想用这样的整数字面量来调用它:

I want to call it with an integer literal like this:

func(0, b);

其中buint32_t.

有什么办法可以在不创建中间变量的情况下做到这一点?
IE.我想避免这样做:

Is there any way I can do this without creating an intermediate variable?
I.e. I want to avoid doing this:

uint32_t a = 0;
func(a, b);

推荐答案

帮助程序类:

struct int_ptr {
    int v;

    operator int *() { return &v; }
};

int foo(int *a, int b);

void bar()
{
    foo(int_ptr{0}, 0);
}

这将导致构造一个临时int_ptr类,将其v成员初始化为0.这将作为参数传递给采用int *的函数,并且int_ptr提供合适的将右指针传递给函数的方法.

This results in a construction of a temporary int_ptr class, initializing its v member to 0. This gets passed as a parameter to a function that takes an int *, and int_ptr provides a suitable operator * method that passes the right pointer to the function.

这整个牌库取决于int_ptr临时目录存在直到函数调用结束的事实.您应该为助手类选择一个名称来强调这一事实.如果您始终使用它将指向0的指针传递给foo,则将其拼写出来:

This entire house of cards hinges on the fact that the int_ptr temporary exists until the end of the function call. You should pick a name for the helper class to underline that fact. If you always use it to pass a pointer to 0 to foo, then spell it out:

struct zero_value_to_foo {
    int v=0;

    operator int *() { return &v; }
};

int foo(int *a, int b);

void bar()
{

    foo(zero_value_to_foo{}, 0);
}

因此在其他情况下使用它看起来很不合适,即

So that using it in other contexts will look to be very much out of place, i.e.

int *p=zero_value_to_foo{};

这可以编译,但是留下一个悬空的指针;但是希望"zero_value_to_foo"标签可以提供一个暗示性的提示,说明这里有问题.

This compiles, but leaves you with a dangling pointer; but hopefully the "zero_value_to_foo" label gives a honking clue that something is wrong here.

要避免误用,您可以做的另一件事是为操作员使用ref限定符:

Another little thing you can do to help yourself from misusing this is to use a ref qualifier for the operator:

struct zero_value_to_foo {
    int v=0;

    operator int *() && { return &v; }
};

有了这个,

foo(zero_value_to_foo{}, 0);

仍然可以编译,但不能编译:

still compiles, but not this:

zero_value_to_foo zero{};

foo(zero, 0);

除了在上下文中意味着这样做以外,可以做更多的工作来使其难以使用.

The more that can be done to make it difficult to use this except in the context is meant for, the fewer opportunities there are for bugs to creep by.

这篇关于有没有一种方法可以在不创建变量的情况下调用需要指针的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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