概念可以与模板模板参数一起使用吗? [英] Can concepts be used with template template parameters?
问题描述
让我们考虑以下代码:
#include <concepts>
template<typename X>
struct Concrete_M {
X f() const { return X{}; }
};
struct Concrete_X {};
template<typename T, typename X>
concept M = requires (T t)
{
{ t.f() } -> std::convertible_to<X>;
};
template<M<Concrete_X>>
struct C {};
const C<Concrete_M<Concrete_X>> c{};
我可以使用以下模板模板参数 T
?
Can I use following template template parameter T
?
template<template<typename> typename T, typename X>
concept M = requires (T<X> t)
{
{ t.f() } -> std::convertible_to<X>;
};
我应该如何更改
template<M<Concrete_X>>
struct C {};
const C<Concrete_M<Concrete_X>> c{};
正确使用更新的概念 M
?我正在寻找这样的东西:
to properly use updated concept M
? I am looking for something like this:
template<typename X, /* ... */>
struct C {};
const C<Concrete_X, /* ... */> c{};
但我不知道应该用什么代替 / *。 .. * /
评论。我尝试过:
but I don't understand what should I put instead of /* ... */
comments. I tried:
template<typename X, M<X>>
struct C {};
const C<Concrete_X, Concrete_M<Concrete_X>> c{};
但GCC 10.0.1会引发错误:
but GCC 10.0.1 raises an error:
(...)'M'不限制类型(...)
(...) ‘M’ does not constrain a type (...)
推荐答案
概念的简化形式 type-constraint 语法:
template <Concept T>
struct C { };
仅对 Concept
的情况有效的第一个模板参数是类型参数。如果不是这种情况,则只需使用长格式语法: requires-clause :
is only valid for those cases where Concept
's first template parameter is a type parameter. When that is not the case, you have to simply use the long form syntax: a requires-clause:
template <template <typename> class Z>
requires M<Z, Concrete_X>
struct C {};
第一个示例的等效长格式为:
The equivalent longer-form for my initial example is:
template <typename T> requires Concept<T>
struct C { };
长格式和短格式表示同一件事-这里没有功能不同。
The long form and short form mean the same thing - there's no functionality different here.
这篇关于概念可以与模板模板参数一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!