用于C ++概念的通配符,说“接受此模板参数的任何内容”

问题描述 投票:0回答:1

是否可以通过提供的任何模板参数允许带有[[template arguments的concept正常?

即模板参数占位符的某种

通配符魔术

一个用法示例:

template<class P, class First, class Second> concept Pair = requires(P p) { std::derived_from<decltype(p.first), First>; std::derived_from<decltype(p.second), Second>; };

用例[a]-接受任何有效的As

对或As:]的子类型// this works well void doWithPairOfA(const Pair<A, A> auto& p) { /* */ }

用例[b]-接受任何有效对,内部类型无限制:

// this is *pseudo code* as Pair<auto, auto> is not allowed void doWithAnyPair(const Pair<auto, auto> auto& p) { /* */ }
很遗憾,auto is not allowed as template argument placeholder in C++20

所以Pair<auto, auto>暂时不是解决方案。


[其他语言以某种方式允许这样的语法,尽管不具有此处要求的确切语义和含义,但是用法看起来非常相似。

Python:

// Any as wildcard foo(lst: List[Any]) -> List[str]

Java:

// ? as wildcard List<String> foo(List<?> lst)

C ++ 20之前的语法看起来像

1

用例[a]-尝试

接受任何有效的As对或As的子类型:
// not as good as with concepts above, this allows only "pair" of A and A // **but rejects sub-types of A, which is not good** // and there is no check that this is actually a pair (can be added with SFINAE) template<template<class, class> typename PAIR> void doWithPairOfA(const PAIR<A, A>& p) { /* */ }

用例[b]-接受任何有效对,内部类型无限制:

// not as good as we would wish - we do allow any kind of "pair" // but there is no check that this is actually a pair (can be added with SFINAE) template<template<class, class> typename PAIR, typename ANY1, typename ANY2> void doWithAnyPair(const PAIR<ANY1, ANY2>& p) { /* */ }
Pre C++20 code

概念可以提供更好的解决方案吗?


1

相关问题(C ++ 20之前的版本,关于模板而不是概念):Templates accepting "anything" in C++是否有一种方法可以让带有模板参数的概念与提供的任何模板参数都可以?即模板参数占位符的某种通配符魔术?一个用法示例:...
c++ templates auto c++20 c++-concepts
1个回答
0
投票
您可以通过修改

Pair

© www.soinside.com 2019 - 2024. All rights reserved.