【问题标题】:Concept or trait for functor with specific arguments?具有特定参数的函子的概念或特征?
【发布时间】:2020-05-18 00:15:36
【问题描述】:

我正在尝试创建一个concept,可用于安全检查函子是否具有特定标准。 这是我现在的代码:

template<typename T>
void fetch(T&& f)
{
  fetch_helper(&f, &std::unwrap_ref_decay_t<T>::operator());
}

template<typename T, typename... Args>
void fetch_helper(T* obj, void (T::*f)(Args...) const)
{
  // do stuff
}

我使用fetch 获取一个函子对象,然后使用fetch_helper 对其进行操作。但是我想实现首选项。 concepttype trait 将检查参数类型是否唯一(我已经为 IsUnique&lt;T...&gt; 实现了概念)。这样如果仿函数不符合标准,程序就不会编译。

// compiles
fetch([](int h){

});

// doesnt compile
fetch([](int h, int j){

});

如何将我的约束 IsUnique 应用于 fetch 中函子对象的参数?我尝试将 requires 概念添加到我的辅助函数中,但这仍然允许使用错误的参数调用 fetch。我必须以某种方式在 fetch 中应用参数的约束。

【问题讨论】:

    标签: c++ template-meta-programming typetraits c++20 c++-concepts


    【解决方案1】:

    像这样?

    template<typename T, typename... Args>
        requires IsUnique<Args...>
    void fetch_helper(T* obj, void (T::*f)(Args...) const) 
    {
      // do stuff
    }
    
    template<typename T>
        requires requires (T&& f) {fetch_helper(&f, &std::unwrap_ref_decay_t<T>::operator());}
    void fetch(T&& f)
    {
      fetch_helper(&f, &std::unwrap_ref_decay_t<T>::operator());
    }
    

    【讨论】:

    • 那不为我编译,我的独特约束没有被应用
    • 没关系一定是做错了什么,它有效
    【解决方案2】:

    如果我没听错的话,你想要这样的东西:

    // TypeTraits if IsUnique is a typical trait inheriting from std::true_type or std::false_type
    template<typename T, typename... Args>
    std::enable_if_t<IsUnique<Args...>::value> fetch_helper(T* obj, void (T::*f)(Args...) const)
    {
      // do stuff
    }
    
    // Concept
    template<typename T, typename... Args> requires (IsUnique<Args...>)
    void fetch_helper(T* obj, void (T::*f)(Args...) const)
    {
      // do stuff
    }
    

    如果您想检查fetch 是否已经存在,您可以添加一个约束条件是否可以使用适当的参数调用fetch_helper(基本上是重复里面的代码)。

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2019-01-21
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      相关资源
      最近更新 更多