【问题标题】:Concept for a class with nested types具有嵌套类型的类的概念
【发布时间】:2017-01-30 09:11:53
【问题描述】:

我正在编写一个概念,该概念要求类具有 ValueType 类型别名并具有静态函数 Check,该函数接受 ValueType 并返回 void

这是我目前所拥有的:

template <typename T>
concept bool Predicate()
{
    return requires(T object)
    {
        typename T::ValueType;
        requires (T::ValueType value)
        {
            {T::Check(value)} -> void;
        };
    };
}

编译时出现以下错误:error: expected ')' before 'value'

【问题讨论】:

  • 啊...C++20...不错...
  • requires requirestypename 将是简约的解决方案。

标签: c++ c++14 c++-concepts


【解决方案1】:

你把问题复杂化了:

template <typename T>
concept bool Predicate = requires(typename T::ValueType obj) {
    { T::Check(obj) } -> void;
};

【讨论】:

  • 如果你想很好地偏序,你仍然需要一个typename T::ValueType;,但是+1。
【解决方案2】:

这是我找到的一个解决方案,它将Predicate 拆分为两个独立的概念:

template <typename T>
concept bool HasCheck()
{
    return requires (typename T::ValueType value)
    {
        {T::Check(value)} -> void;
    };
};

template <typename T>
concept bool Predicate()
{
    return requires(T object)
    {
        typename T::ValueType;
        requires HasCheck<T>();
    };
}

wandbox example


或者,您可以将requires 子句与&amp;&amp; 链接起来:

template <typename T>
concept bool Predicate()
{
    return requires(T object)
    {
        typename T::ValueType;        
    } 
    && requires (typename T::ValueType value)
    {
        {T::Check(value)} -> void;
    };
}

wandbox example

【讨论】:

  • 谢谢,我还发现我不需要T object 部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2022-01-22
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
相关资源
最近更新 更多