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

标签 c++ function struct arguments parameter-passing

我有一个结构定义为:

struct Foo
{
    double x;
    double y;
};

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

void doSomethingWithFoo(Foo foo);

我还想通过直接传递结构成员来使用这个函数:

void doSomethingWithFoo(double x, double y);

有没有一种方法可以使用 std::allocator_traits::construct 或任何其他方法来在不显式定义第二个函数的情况下做到这一点?

最佳答案

您可以直接执行此操作:doSomethingWithFoo({ 1, 2 });。编译器知道 doSomethingWithFoo 采用 Foo 类型,因此它会寻找从您给它的 (int, int) 到 的转换>富。作为一个简单的“普通旧数据”(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;
}

打印:

1, 2

关于c++ - 如何使用 std::allocator_traits::construct 从函数参数创建结构对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57461013/

相关文章:

c++ - 将固定长度的数据从 std::istream 复制到字符串

c++ - 为什么不在 C++ 游戏中频繁分配和释放内存?

c++ - 从子类调用非虚方法

c++ - 未命名结构的前向声明

c - C中的结构内存布局

c++ - void 函数返回 Int 和 Void

c++ - 如何将特殊字符作为标题文本的一部分插入到 QMenu 中?

c++ - 防止两种方法共享相同的代码?

python - 返回 Python 中的封闭范围变量

c# - 将复杂结构从 C++ 编码到 C#