SFINAE离开了副本构造函数 [英] SFINAE away a copy constructor

查看:63
本文介绍了SFINAE离开了副本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我想SFINAE删除类模板的复制构造函数和复制赋值运算符。但是,如果这样做,则会生成默认的复制构造函数和默认的赋值运算符。 SFINAE是基于我作为类模板参数传递的标签完成的。问题是SFINAE仅适用于模板,而复制构造函数/赋值运算符不能用作模板。是否存在解决方法?

Under certain conditions, I'd like to SFINAE away the copy constructor and copy assignment operator of a class template. But if I do so, a default copy constructor and a default assignment operator are generated. The SFINAE is done based on tags I pass as class template parameters. The problem is, that SFINAE only works on templates and a copy constructor/assignment operator can't be a template. Does there exist a workaround?

推荐答案

此解决方案使用有条件不可复制的基类(通过显式标记复制构造函数和

This solution uses a base class that is conditionally not copyable (by explicitely marking the copy constructor and copy assignment operator as deleted).

template <bool>
struct NoCopy;

template <>
struct NoCopy<true>
{
   // C++11 and later: marking as deleted. Pre-C++11, make the copy stuff private.
   NoCopy(const NoCopy&) = delete;
   NoCopy& operator=(const NoCopy&) = delete;
   protected:
      ~NoCopy() = default; // prevent delete from pointer-to-parent
};

template <>
struct NoCopy<false>
{
   // Copies allowed in this case
   protected:
      ~NoCopy() = default; // prevent delete from pointer-to-parent
};

示例用法:

template <typename Number>
struct Foo : NoCopy<std::is_integral<Number>::value>
{
   Foo() : NoCopy<std::is_integral<Number>::value>{}
   {
   }
};

int main()
{
   Foo<double> a;
   auto b = a; // compiles fine
   Foo<int> f;
   auto g = f; // fails!
}

注意: NoCopy 被声明为受保护的,以避免虚拟继承(感谢提示,@ Yakk)。

Note: the destructor of NoCopy is declared protected to avoid virtual inheritance (Thanks for the hint, @Yakk).

这篇关于SFINAE离开了副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆