键入trait以检查参数包中的所有类型是否都是可复制的 [英] Type trait to check that all types in a parameter pack are copy constructible

查看:97
本文介绍了键入trait以检查参数包中的所有类型是否都是可复制的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个类型trait来检查参数包中的所有类型是否都是可复制的。这是我到目前为止做的。主要功能包含一些测试用例,以检查功能。

I need a type trait to check whether all types in a parameter pack are copy constructible. This is what I've done so far. The main function contains some test cases, to check the functionality.

#include <type_traits>
#include <string>
#include <memory> 

template <class... Args0toN>
struct areCopyConstructible;

template<>
struct areCopyConstructible<> : std::true_type {};

template <class Arg0, class... Args1toN, class std::enable_if< !std::is_copy_constructible<Arg0>::value>::type* = nullptr >
struct areCopyConstructible : std::false_type {};

template <class Arg0, class... Args1toN, class std::enable_if< std::is_copy_constructible<Arg0>::value>::type* = nullptr >
struct areCopyConstructible : areCopyConstructible<Args1toN...> {};

int main()
{
  static_assert(areCopyConstructible<>::value, "failed");
  static_assert(areCopyConstructible<int>::value, "failed");
  static_assert(areCopyConstructible<int, std::string>::value, "failed");
  static_assert(!areCopyConstructible<std::unique_ptr<int> >::value, "failed");
  static_assert(!areCopyConstructible<int, std::unique_ptr<int> >::value, "failed");
  static_assert(!areCopyConstructible<std::unique_ptr<int>, int >::value, "failed");
}

链接到活示例

我的想法是递归检查,包的head元素是否是可复制构造的进一步,与尾巴。不幸的是,我没有这个想法编译。我对可变模板的了解不是很先进。我想,启用,如果在模板列表中的参数包后不工作。我不知道。

My idea was to check recursively, whether the head element of the pack is copy-constructible or not and go on further, with the tail. Unfortunately, I do not get this idea to compile. My knowledge about variadic templates is not very advanced. I guess, that enable-if after parameter pack in template list does not work. I have no idea. Does anyone has a good advice, how to solve the problem?

推荐答案

首先定义一个可重用的实用程序来测试每个谓词是否在pack is true:

First define a reusable utility to test whether every predicate in a pack is true:

template<typename... Conds>
  struct and_
  : std::true_type
  { };

template<typename Cond, typename... Conds>
  struct and_<Cond, Conds...>
  : std::conditional<Cond::value, and_<Conds...>, std::false_type>::type
  { };

然后使用 is_copy_constructible (或任何其他一元类型特性):

Then it's trivial to use that with is_copy_constructible (or any other unary type trait):

template<typename... T>
  using areCopyConstructible = and_<std::is_copy_constructible<T>...>;

像这样定义和_ 它会短路,即在第一个错误结果后停止实例化 is_copy_constructible 包的剩余部分。

One advantage of defining and_ like this is that it short-circuits, i.e. stops instantiating is_copy_constructible for the rest of the pack after the first false result.

这篇关于键入trait以检查参数包中的所有类型是否都是可复制的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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