c – 检查可变参数模板声明中的参数类型
作者:互联网
我得到了一个简单的可变参数模板声明,就像经典的一样:
template <typename... Arguments>
class VariadicTemplate;
我需要实现的是让VariadicTemplate类执行某些类型检查;可变参数模板应以某种迭代形式检查接收到的所有参数应该说出类型< Foo>.
我在某个地方看到了类似的东西,但现在我无法辨认它在哪里:P
解决方法:
struct Foo {};
#include <type_traits>
template<class T, class...>
struct are_same : std::true_type
{};
template<class T, class U, class... TT>
struct are_same<T, U, TT...>
: std::integral_constant<bool, std::is_same<T,U>{} && are_same<T, TT...>{}>
{};
template<typename... Arguments>
class VariadicTemplate
{
static_assert(are_same<Foo, Arguments...>{}, "a meaningful error message");
};
int main()
{
VariadicTemplate<Foo, Foo, Foo, Foo> v0{}; (void)v0;
VariadicTemplate<Foo, int, Foo, double> v1{}; (void)v1;
}
但有些东西告诉我你想知道参数是否是类模板Foo的所有特化:
template<class T, class U>
struct Foo {};
#include <type_traits>
template<template<class...> class T, class U>
struct is_template_of
{
template<class... TT>
static std::true_type test(T<TT...>*);
static std::false_type test(...);
constexpr static bool value = decltype(test((U*)nullptr)){};
};
template<template<class...> class T, class...>
struct is_template_of_N : std::true_type
{};
template<template<class...> class T, class U, class... TT>
struct is_template_of_N<T, U, TT...>
: std::integral_constant<bool, is_template_of<T,U>::value
&& is_template_of_N<T, TT...>{}>
{};
template<typename... Arguments>
class VariadicTemplate
{
static_assert(is_template_of_N<Foo, Arguments...>{},
"a meaningful error message");
};
int main()
{
VariadicTemplate<Foo<int, double>, Foo<int, int>> v0; (void)v0;
VariadicTemplate<Foo<int, double>, int> v1; (void)v1;
}
标签:variadic,c,templates 来源: https://codeday.me/bug/20190725/1532407.html