我是一位有用的助手,可以为您翻译文本。
我正在进行一些模板元编程,并希望实现一个通用克隆函数,根据SFINAE(替换失败不是错误)中的表达式有效性选择克隆方法。
在这个参考网站上,它说:
应该完全等同于
即使我有其他的
如果
这是一个小例子,在启用C++14的GCC 5.3上编译失败:
我正在进行一些模板元编程,并希望实现一个通用克隆函数,根据SFINAE(替换失败不是错误)中的表达式有效性选择克隆方法。
在这个参考网站上,它说:
该函数
make_unique<T>( std::forward<Args>(args)... )
这是否意味着以下代码:is equivalent to:
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);
}
应该完全等同于
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) );
}
即使我有其他的
my_clone
函数重载, std::make_unique()
在语义上是否符合SFINAE?换句话说: 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() );
}
make_unique
返回:unique_ptr<T>(new T(std::forward<Args>(args)...))
。 - NathanOliverT
不能使用Args&&...
构造,则std::make_unique(Args&&...)
不存在。 - Holtstd::is_copy_constructible
特性。 - Jarod42