我有一个结构定义为:
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/