Select function based on if template is pointer/reference or none

  • A+
Category:Languages

I would like to provide different implementations of a function dependant on if it is a pointer, a reference or a regular type. This is my code so far:

template<class T,          class = typename std::enable_if_t<std::is_reference<T>::value>> void f(T && in) {}  // This causes redefinition error  template<class T,     class = typename std::enable_if_t<std::is_pointer<T>::value>> void f(T && in) {}  template<class T,     class = typename std::enable_if_t<!std::is_reference<T>::value>,     class = typename std::enable_if_t<!std::is_pointer<T>::value>> void f(T && in) {} 

The middle function causes:

12:13: error: redefinition of 'template void f(T&&)'

7:13: note: 'template void f(T&&)' previously declared here

Funnily only the first and last function together compile.

Any ideas how to fix it or simplify this code.

 


Template default argument values are not part of the signature, so you need to further disambiguate the overloads by - as an example - adding an extra dummy template parameter:

template<class T,          class = typename std::enable_if_t<std::is_reference<T>::value>> void f(T && in) {}  // This causes redefinition error  template<class T,     class = typename std::enable_if_t<std::is_pointer<T>::value>, class = void> void f(T && in) {} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: