Ral*_*zky 3 c++ sfinae unique-ptr c++11
我正在做一些模板元编程,我想实现一个通用的克隆函数,它根据SFINAE表达式的有效性选择克隆方法(替换失败不是错误).
在这个参考网站上它说
功能
make_unique<T>( std::forward<Args>(args)... )
Run Code Online (Sandbox Code Playgroud)
相当于:
Run Code Online (Sandbox Code Playgroud)unique_ptr<T>(new T(std::forward<Args>(args)...))
这是否意味着以下代码
template <typename T>
auto my_clone( const T & t ) -> decltype( std::make_unique<T>(t) )
{
return std::make_unique<T>(t);
}
Run Code Online (Sandbox Code Playgroud)
应完全等同于
template <typename T>
auto my_clone( const T & t ) -> decltype( std::unique_ptr<T>( new T(t) ) )
{
return std::unique_ptr<T>( new T(t) );
}
Run Code Online (Sandbox Code Playgroud)
即使我有其他功能的重载my_clone
?换句话说:std::make_unique()
SFINAE友好吗?
如果T
是没有拷贝构造的,那么后者的代码不会因SFINAE参与重载决议.
这是一个小例子,无法在启用C++ 14的GCC 5.3上编译:
#include <memory>
// It does **not** work with this snippet:
template <typename T>
auto my_clone( const T & t ) -> decltype( std::make_unique<T>( t ) )
{
return std::make_unique<T>( t );
}
/* // But it works with this snippet instead:
template <typename T>
auto my_clone( const T & t ) -> decltype( std::unique_ptr<T>( new T(t) ) )
{
return std::unique_ptr<T>( new T(t) );
}*/
// This is another overload for testing purposes.
template <typename T>
auto my_clone( const T & t ) -> decltype(t.clone())
{
return t.clone();
}
class X
{
public:
X() = default;
auto clone() const
{
return std::unique_ptr<X>( new X(*this) );
}
private:
X( const X & ) = default;
};
int main()
{
// The following line produces the compiler error:
// "call to 'my_clone' is ambiguous"
const auto x_ptr = my_clone( X() );
}
Run Code Online (Sandbox Code Playgroud)
该标准仅保证:
template <class T, class... Args> unique_ptr<T> std::make_unique(Args&&... args);
Run Code Online (Sandbox Code Playgroud)
...必须返回unique_ptr<T>(new T(std::forward<Args>(args)...))
,它不保证该make_unique
功能只有在T
可构造使用时才存在Args...
,因此它不是SFINAE友好的(按照标准),所以你不能依赖它.
标准中唯一提到的部分make_unique
:
§20.8.1.4[unique.ptr.create]:
Run Code Online (Sandbox Code Playgroud)template <class T, class... Args> unique_ptr<T> make_unique(Args&&... args);
- 备注:除非T不是数组,否则此函数不应参与重载决策.
- 返回:
unique_ptr<T>(new T(std::forward<Args>(args)...))
.
在您的情况下,您可能希望使用该版本std::unique_ptr<T>(new T(...))
或用于is_copy_constructible
使您的my_clone
SFINAE友好(@Yakk,@ Jarod42),例如:
template <typename T,
typename = std::enable_if_t<std::is_copy_constructible<T>::value>>
auto my_clone(const T & t) -> decltype(std::make_unique<T>(t)) {
return std::make_unique<T>(t);
}
Run Code Online (Sandbox Code Playgroud)