如何使用std :: allocator_traits :: construct从函数参数创建结构对象?

loc*_*e14 0 c++ struct arguments function parameter-passing

我有一个结构定义为:

struct Foo
{
    double x;
    double y;
};
Run Code Online (Sandbox Code Playgroud)

我有一个函数将此结构作为参数:

void doSomethingWithFoo(Foo foo);
Run Code Online (Sandbox Code Playgroud)

我还想通过直接传递struct成员来使用此功能:

void doSomethingWithFoo(double x, double y);
Run Code Online (Sandbox Code Playgroud)

std::allocator_traits::construct没有明确定义第二个功能,是否有一种使用方式或任何其他方式能够做到这一点?

Fro*_*yne 5

您可以直接执行以下操作:doSomethingWithFoo({ 1, 2 });。编译器知道doSomethingWithFoo采用Foo类型,因此会寻找从您给它(int, int)到的转换Foo。作为简单的“普通旧数据”(POD)类型,初始化器列表中的构造函数是隐式的,并且可以正常工作。

struct Foo
{
    double x;
    double y;
};

void doSomethingWithFoo(Foo foo)
{
    std::cout << foo.x << ", " << foo.y << std::endl;
}

int main()
{
    doSomethingWithFoo({ 1, 2 });

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

印刷品:

1, 2
Run Code Online (Sandbox Code Playgroud)