我可以根据属性重载函数模板吗?

Can I overload function templates based on properties?

我想从 classes 的不同家族中得到一个共同的 属性。对于一些,我可以只使用一个成员,对于一些我需要调用一个函数。 我能否以某种方式重载模板函数,以便编译器根据 class 是否具有 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;
}

您可以使用 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;
}

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;
}