c++ Concepts TS会启用多个参数包吗?

Will the C++ Concepts TS enable multiple parameter packs?

本文关键字:参数 包吗 启用 Concepts TS c++      更新时间:2023-10-16

在c++ 14中,不可能调用带有多个参数包的函数模板:

#include <future>
template<class... Futures, class... Incrementables>
void foo(Futures&... futures, Incrementables... incrementables)
{
}
int main()
{
  std::future<int> a, b;
  int x, y;
  // ERROR
  foo(a, b, x, y);
  return 0;
}

因为不清楚第一个参数包在哪里结束,第二个参数包在哪里开始,所以如果没有程序员提供的额外信息,就不可能调用foo

然而,似乎这两个参数包在原则上可以消除歧义,给FutureIncrementable适当的概念。

即将发布的c++概念技术规范是否会放宽这些限制,允许调用具有多个参数包的函数模板?

Concepts Lite的约束系统位于现有模板机制之上。特别是,它不会干扰模板参数的推导。在您的示例中,Futures包是不可演绎的,并且即使使用概念也将保持如此。

然而,似乎这两个参数包在原则上可以消除歧义,给予适当的Future和Incrementable概念。

你可能没有选到最好的例子,尽管这并不会让你的问题的前提变得不那么有趣。你怎么看这个?

Future{Fut}
struct incrementable_future: Fut {
    using Fut::Fut;
    incrementable_future& operator++() { return *this; }
};

在c++ 14中,不可能调用包含多个参数包的函数模板

正如在对这个问题的评论中提到的,只要这些包可以推导出来,即使在c++ 14中也是可能的。
它遵循一个最小的工作示例:

#include <tuple>
#include<functional>
template<class... T, std::size_t... I, typename... U>
void foo(std::tuple<T...> ts, std::index_sequence<I...>, std::tuple<U...> us)
{ }
int main() {
    foo(std::make_tuple(42, 'b'), std::make_index_sequence<10>(), std::make_tuple(0., 'c'));
    return 0;
}
另一种方法是通过模板特化:
template<typename, typename>
struct S;
template<typename R1, typename... A1, typename R2, typename... A2>
struct S <R1(A1...), R2(A2...)> {};
int main() {
    S<void(int, char), int(char, float, double)> s;
}

这里是第三个不需要std::tuple或其他工件的例子:

template<typename... A, typename... B>
void f(B...) { }
int main() {
    f<int, char>(42, 0.);
}

这里的技巧在于参数包A是在函数调用时显式指定的,而参数包B是从函数实参中推导出来的。

这表明即使使用c++ 11,您也可以轻松地提供多个参数包,而无需等待概念。