我需要一个类型特征来检查参数包中的所有类型是否都是可复制构造的。这是我到目前为止所做的。 main 函数包含一些测试用例,用于检查功能。
#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");
}
我的想法是递归检查包的头部元素是否可复制构造,然后继续使用尾部。不幸的是,我没有编译这个想法。我对可变参数模板的了解不是很高级。我猜,模板列表中的参数包后的 enable-if 不起作用。我不知道。有没有人有好的建议,如何解决这个问题?
最佳答案
首先定义一个可重用的实用程序来测试包中的每个谓词是否为真:
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
(或任何其他一元类型特征)一起使用是微不足道的:
template<typename... T>
using areCopyConstructible = and_<std::is_copy_constructible<T>...>;
像这样定义 and_
的一个优点是它会短路,即在第一个错误结果之后停止为包的其余部分实例化 is_copy_constructible
。
关于c++ - 类型特征以检查参数包中的所有类型是否都是可复制构造的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29603364/