0
template<typename ...>
bool foo(std::tuple<std::string,float> bar...)
{
    std::vector<std::tuple<std::string,float>> barList(bar...);

    // ...
}

这似乎不会产生任何语法错误。编辑器中该行没有错误指示符,但编译器停止

[bcc32c 错误] Foo.cpp(117):包扩展不包含任何未扩展的参数包

我试图在网上阅读,但我发现的所有示例要么似乎不完整,要么我不清楚。

一个简单的答案为什么不能编译将不胜感激。

4

1 回答 1

2

你的语法是错误的。您的功能等同于:

bool foo(int bar...)
{
    std::vector<int> barList(bar...);

    // ...
}

请注意,根本没有可变参数模板,也没有什么可解压的——相反,您创建了一个 C 风格的可变参数函数。

更改功能的一种最简单方法是:

template<typename... Args>
bool foo(Args... bar)
{
    std::vector<std::tuple<std::string,float>> barList({bar...});

    // ...
}

This is not ideal, as it makes your template function quite greedy - it will gladly consume any arguments, not just tuples of strings and floats.

We can spice it up by using C++20 concepts:

template<class T>
concept Tuple = std::is_same_v<T, std::tuple<std::string, float>>;

template<Tuple... T>
bool foo(T... bar)
{
    std::vector<std::tuple<std::string, float>> barList({bar...});

    // ...
    return true;
}

This allows usage like that:

foo(std::tuple<std::string, float>{"ddd", 20}, std::tuple<std::string, float>{"ddd", 20});

But not like that:

foo(10, 20, nullptr);
于 2021-06-18T19:07:18.243 回答