概念可以与模板模板参数一起使用吗?
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
吗?
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
?我正在寻找这样的东西:
template<typename X, /* ... */>
struct C {};
const C<Concrete_X, /* ... */> c{};
但我不明白我应该用什么来代替 /* ... */
评论。我试过了:
template<typename X, M<X>>
struct C {};
const C<Concrete_X, Concrete_M<Concrete_X>> c{};
但 GCC 10.0.1 引发错误:
(...) ‘M’ does not constrain a type (...)
概念的简写 type-constraint 语法:
template <Concept T>
struct C { };
仅对Concept
的第一个模板参数是类型参数的情况有效。如果不是这种情况,您必须简单地使用长格式语法:a requires-clause:
template <template <typename> class Z>
requires M<Z, Concrete_X>
struct C {};
我的初始示例的等效长格式是:
template <typename T> requires Concept<T>
struct C { };
长格式和短格式的意思是一样的 - 这里没有功能上的不同。
让我们考虑以下代码:
#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
吗?
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
?我正在寻找这样的东西:
template<typename X, /* ... */>
struct C {};
const C<Concrete_X, /* ... */> c{};
但我不明白我应该用什么来代替 /* ... */
评论。我试过了:
template<typename X, M<X>>
struct C {};
const C<Concrete_X, Concrete_M<Concrete_X>> c{};
但 GCC 10.0.1 引发错误:
(...) ‘M’ does not constrain a type (...)
概念的简写 type-constraint 语法:
template <Concept T>
struct C { };
仅对Concept
的第一个模板参数是类型参数的情况有效。如果不是这种情况,您必须简单地使用长格式语法:a requires-clause:
template <template <typename> class Z>
requires M<Z, Concrete_X>
struct C {};
我的初始示例的等效长格式是:
template <typename T> requires Concept<T>
struct C { };
长格式和短格式的意思是一样的 - 这里没有功能上的不同。