简体   繁体   中英

Why SFINAE doesn't work in this example?

#include <iostream>
#include <type_traits>

class CL
{
    public:
    CL(){}
    CL( int ) = delete;
};

template < class T >
class Creator
{
public:
    template< std::enable_if_t< std::is_constructible<T, int>::value, int > = 0 >
    static T* Create( int arg ) // 1
    {
        return new T( arg );
    }
    template< std::enable_if_t< std::is_default_constructible<T>::value && !std::is_constructible<T, int>::value, int > = 0 >
    static T* Create( int arg ) // 2
    {
        return new T();
    }
};

int main()
{
    Creator<CL>::Create( 2 );
}

Here I give error that the first Create function can't deduce template argument, but then I commented it, the second overload is works fine. Why SFINAE doesn't work on first overload?

Your method is not template, it is your class which is template. You had to change

template<typename U = T,
         std::enable_if_t< std::is_constructible<U, int>::value, int > = 0 >
static T* Create( int arg ) // 1
{
    return new T( arg );
}

template<typename U = T,
         std::enable_if_t< std::is_default_constructible<U>::value
                          && !std::is_constructible<U, int>::value, int > = 0 >
static T* Create( int arg ) // 2
{
    return new T();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM