Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 461
omicronns Avatar asked Nov 30 '25 02:11

omicronns


1 Answers

In the second case you have a non-deduced context, in other words, the compiler cannot deduce the type.

The simplest example of a non-deduced context is

template<typename T>
struct Id
{
    using type = T;
};

template<typename T>
void foo(typename Id<T>::type arg); // T cannot be deduced
like image 110
vsoftco Avatar answered Dec 01 '25 15:12

vsoftco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!