在C++中,如何使用模板接受任意格式的聚合初始化列表?

问题描述 投票:0回答:1

例如,考虑函数 foo,可以按如下方式调用它:

foo(
    {{1.0f}, 123},
    {'c', {}}
);

函数中的每个参数位置都可以采用聚合初始化列表(聚合初始化),形成任意深度的树状结构。

我的现实目标是为任意 protobuf 类编写一个模板构造函数。我相信这可以通过前面提到的模板功能与动态反射相结合来实现。

有可用的解决方案吗,或者有什么原因无法实现吗?

c++ protocol-buffers variadic-templates c++-templates
1个回答
0
投票

有没有可用的解决方案

是的,有点

struct nested
{
    nested(int) {}
    nested(char) {}
    nested(double) {}
    nested(float) {}
    template<size_t N>
    nested(const char (&)[N]) {}
    nested(std::initializer_list<nested>) {}
};

void foo(nested) {}

并用作

foo({{{1.0f}, 123}, {'c', {}}});
foo({1, {'2', "3", {4., {5}}}});

注意额外的顶级括号。

由于

{...}
不是表达式,因此永远无法推断参数的类型,从而排除了可变参数模板的使用。你总是可以走老路,写出你想要的所有数量

void foo(nested) {}
void foo(nested, nested) {}
...

但显然这并不理想。

© www.soinside.com 2019 - 2024. All rights reserved.