如何将带有两个参数包的requires子句提取到一个概念中



我有一个(据说不太有用(带有模板化构造函数的类模板,它是完美转发的候选者。I、 但是,希望确保传递给构造函数的类型与为整个类指定的类型完全相同(没有cvref限定符(:

template <typename... Ts>
struct foo {
template <typename... CTs>
requires (std::same_as<std::remove_cvref_t<Ts>, std::remove_cvref_t<CTs>> && ...)
foo(CTs&& ...) {
std::cout << "called with " << (sizeof...(CTs)) << " argsn";
}
};

现在我可以制作:

auto f = foo<int, int>(1, 1);

我做不到:

auto f = foo<float, int>(1, 1);

这很好。


但我想将requires ...体提取为concept:

template <typename... T1s, typename... T2s>
concept same_unqualified_types = (
std::same_as<
std::remove_cvref_t<T1s>,
std::remove_cvref_t<T2s>
> && ...
);
template <typename... Ts>
struct foo {
template <typename... CTs>
requires same_unqualified_types<Ts..., CTs...>
foo(CTs&& ...) {                // 16
std::cout << "called with " << (sizeof...(CTs)) << " argsn";
}
};
int main() {
auto f = foo<int, int>(1, 1);   // 22
}

但这给了我一个错误:

main.cpp: In function 'int main()': 
main.cpp:22:32: error: no matching function for call to 'foo<int, int>::foo(int, int)'
22 |     auto f = foo<int, int>(1, 1);
|   
main.cpp:16:5: note: candidate: 'template<class ... CTs>  requires  same_unqualified_types<Ts ..., CTs ...> foo<Ts>::foo(CTs&& ...) [with CTs = {CTs ...}; Ts = {int, int}]'
16 |     foo(CTs&& ...) {
|     ^~~
main.cpp:16:5: note:   template argument deduction/substitution failed:
main.cpp:16:5: note: constraints not satisfied
main.cpp: In substitution of 'template<class ... CTs>  requires  same_unqualified_types<Ts ..., CTs ...> foo<int, int>::foo(CTs&& ...) [with CTs = {int, int}]':
main.cpp:22:32:   required from here
main.cpp:5:9:   required for the satisfaction of 'same_unqualified_types<Ts ..., CTs ...>' [with CTs = {int, int}; Ts = {int, int}]
main.cpp:22:32: error: mismatched argument pack lengths while expanding 'same_as<typename std::remove_cvref<T1s>::type, typename std::remove_cvref<T2s>::type>'
22 |     auto f = foo<int, int>(1, 1);
|    

我想我可能对concept same_unqualified_types做了一些错误的事情,因为我正在尝试使用两个参数包。我试过手动测试它,但它似乎不起作用,即使我做same_unqualified_types<int, int>same_unqualified_types<int, int, Pack...>,其中Pack...是两个int的参数包。

我的逻辑哪里有缺陷?我可以将requires子句提取为concept吗?

免责声明:我知道我可以通过CTAD和推理指南实现类似的目标,甚至不需要任何概念。我只是想知道我的理解哪里有缺陷。

概念在模板参数包方面没有特殊权限。一组模板参数中不能有两个包,除非有东西可以根据传递给它们的参数来区分它们(一个可以是一系列类型,另一个是一系列值,或者你可以访问模板参数推导来区分它们,或者类似的东西(。

你能做的最好的事情就是创建一个不合格的same_as等价物,并根据需要将其用于包扩展:


template<typename T, typename U>
concept same_as_unqual = std::same_as<<std::remove_cvref_t<T>, <std::remove_cvref_t<U>>;
template <typename... Ts>
struct foo {
template <typename... CTs>
requires (same_as_unqual<Ts, CTs> && ...)
...

在参数之间进行成对比较的单一概念是不可能的。嗯,这是可能的,但它会更加详细,因为您可能需要将它们捆绑在某种类型列表中。我不认为same_as_all<type_list<Ts...>, type_list<Us...>>比做一个显式扩展更好。

最新更新