0

我有这个(据说不是那么有用)类模板和模板化构造函数,它是完美转发的候选者。但是,我想确保传递给构造函数的类型与为整个类指定的类型完全相同(没有 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 和演绎指南实现类似的目标 - 甚至不需要任何概念。我只想知道我的理解哪里有缺陷。

4

1 回答 1

2

概念没有获得关于模板参数包的特殊权限。一组模板参数中不能有两个包,除非根据传递给它们的参数可以区分它们(一个可能是一系列类型,另一个是一系列值,或者您可以访问模板论证推论以区分它们,或类似的东西)。

您将能够做的最好的事情是创建一个不合格的等效项,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...>>比进行显式扩展更好的了。

于 2021-11-14T19:34:12.817 回答