是否可以通过提供的任何模板参数允许带有[[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>;
};
对或As:]的子类型用例[a]-接受任何有效的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++是否有一种方法可以让带有模板参数的概念与提供的任何模板参数都可以?即模板参数占位符的某种通配符魔术?一个用法示例:...Pair