我有这个(据说不是那么有用)类模板和模板化构造函数,它是完美转发的候选者。但是,我想确保传递给构造函数的类型与为整个类指定的类型完全相同(没有 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)) << " args\n";
}
};
现在我可以做:
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)) << " args\n";
}
};
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>
or ,两个s的参数包same_unqualified_types<int, int, Pack...>
在哪里。Pack...
int
我的逻辑哪里有问题?我可以将该requires
子句提取到 aconcept
吗?
免责声明:我知道我可以通过 CTAD 和演绎指南实现类似的目标 - 甚至不需要任何概念。我只想知道我的理解哪里有缺陷。