为什么 SFINAE 在此示例中不起作用?
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 );
}
这里我给出了第一个Create函数无法推导模板参数的错误,但后来我评论了它,第二个重载工作正常。为什么 SFINAE 在第一次重载时不起作用?
你的方法不是模板,是你的class是模板。你必须改变
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();
}
#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 );
}
这里我给出了第一个Create函数无法推导模板参数的错误,但后来我评论了它,第二个重载工作正常。为什么 SFINAE 在第一次重载时不起作用?
你的方法不是模板,是你的class是模板。你必须改变
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();
}