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

Fab*_*ian 3 c++ templates overloading

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

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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)