omicronns omicronns - 2 months ago 16
C++ Question

C++ template parameter deduction fails

Why compiler can deduce T with this code:

#include <vector>

template<typename T>
void foo(T& t) {}

int main(void) {
std::vector<uint8_t> vec = { 1,2,3 };
foo(vec);
return 0;
}


But fails with this code:

#include <vector>
#include <type_traits>

template<typename T>
void foo(typename std::enable_if<true, T>::type& t) {}

int main(void) {
std::vector<uint8_t> vec = { 1,2,3 };
foo(vec);
return 0;
}


I want to use second construct, to select between two template functions, based on passed class method existence.

Answer

As explained by vsoftco, you have a non-deduced context.

For SFINAE, you may use one of the following:

template<typename T>
std::enable_if_t<condition_dependent_of_T, ReturnType>
foo(T& t) {}

or

template<typename T, std::enable_if_t<condition_dependent_of_T>* = nullptr>
ReturnType foo(T& t) {}