Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

sfinae

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.

like image 961
Andreas Pasternak Avatar asked Dec 05 '22 10:12

Andreas Pasternak


1 Answers

The usual way is to provide appropriate overloads:

#include <iostream>

template <class T> void f(T&&) {
    std::cout << "T&&\n";
}

template <class T> void f(T*) {
    std::cout << "T*\n";
}

template <class T> void f(T&) {
    std::cout << "T&\n";
}

int main() {
    int i;
    f(std::move(i));
    f(&i);
    f(i);
}

This produces the following output:

[temp]$ clang++ -std=c++11 test.cpp
[temp]$ ./a.out
T&&
T*
T&
[temp]$ 
like image 185
Pete Becker Avatar answered Dec 31 '22 10:12

Pete Becker