【问题标题】:Can I overload function templates based on properties?我可以根据属性重载函数模板吗?
【发布时间】:2021-01-29 06:40:01
【问题描述】:

我想从不同的类家族中获得一个共同的属性。对于一些人,我可以只使用一个成员,对于一些人我需要调用一个函数。 我能否以某种方式重载模板函数,以便编译器根据类是否具有functionAfunctionBmember 来选择合适的模板函数?目前我收到错误,因为我多次定义相同的模板函数...

template<class TypeWithFunctionA>
int doSomething(const TypeWithFunctionA & h)
{
  return h.functionA();
}

template<class TypeWithFunctionB>
int doSomething(const TypeWithFunctionB & h)
{
  return h.functionB();
}

template<class TypeWithMember>
int doSomething(const TypeWithMember & h)
{
  return h.member;
}

【问题讨论】:

    标签: c++ templates overloading


    【解决方案1】:

    您可以使用SFINAE 重载它们。例如

    template<class TypeWithFunctionA>
    auto doSomething(const TypeWithFunctionA & h) -> decltype(h.functionA())
    {
      return h.functionA();
    }
    
    template<class TypeWithFunctionB>
    auto doSomething(const TypeWithFunctionB & h) -> decltype(h.functionB())
    {
      return h.functionB();
    }
    
    template<class TypeWithMember>
    auto doSomething(const TypeWithMember & h) -> decltype(h.member)
    {
      return h.member;
    }
    

    【讨论】:

    • 如果我不返回一个 int 而是一个 const 引用来表示 std::string,这是否也有效?如果 h.member 是 std::string,那么字符串将被复制,我想避免这样做。
    • @Fabian 你必须指定返回类型为-&gt; const decltype(h.member)&amp;
    【解决方案2】:

    C++20 让这变得非常直截了当:

    template <class TypeWithFunctionA>
    int doSomething(const TypeWithFunctionA &h)
    requires requires{h.functionA();}
    {
        return h.functionA();
    }
    
    template <class TypeWithFunctionB>
    int doSomething(const TypeWithFunctionB &h)
    requires requires{h.functionB();}
    {
        return h.functionB();
    }
    
    template <class TypeWithMember>
    int doSomething(const TypeWithMember &h)
    requires requires{h.member;}
    {
        return h.member;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2016-07-30
      相关资源
      最近更新 更多