Question

I am getting a SFINAE error with the following code as it will not use the template. I am trying to perfect forward the args in as the result. Any ideas anyone.

#include <iostream>

#include "constants.h"


namespace perfectforwarding
{
    template<class T, class U>
    constexpr auto maximum(T&& a, U&& b) -> decltype( (a > b) ? std::forward(a) : std::forward(b))
    {
        return (a > b) ? std::forward(a) : std::forward(b);
    }
}



int main(int argc, const char * argv[])
{

    std::cout << "Created count is: " << created_count << std::endl;

    auto const result = perfectforwarding::maximum(5,6.0);

    std::cout << "The maximum of 5 and 6: " << result << std::endl;
    return 0;
}

Blair

Was it helpful?

Solution

std::forward is a template, and you need to provide the type argument explicitly if you want it to work properly. This is how your maximum function template should be rewritten:

template<class T, class U>
constexpr auto maximum(T&& a, U&& b) -> 
    decltype( (a > b) ? std::forward<T>(a) : std::forward<U>(b))
{
    return (a > b) ? std::forward<T>(a) : std::forward<U>(b);
}

This is how the std::forward utility is defined:

template<class T> 
T&& forward(typename remove_reference<T>::type& a) noexcept
{
    return static_cast<S&&>(a);
}

The expression typename remove_reference<T>::type makes this a non-deduced context, which explains why type deduction fails if you do not explicitly provide the type argument T.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top