检查可变模板声明中的参数类型 [英] Check for arguments type in a variadic template declaration
本文介绍了检查可变模板声明中的参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的可变参数模板声明,就像经典的模板声明:
I got a plain variadic template declaration, just like the classic one:
template <typename... Arguments>
class VariadicTemplate;
我需要实现的是让 VariadicTemplate
class do执行一些类型检查;可变参数模板应该以一些迭代形式检查所有接收到的参数是否应该说类型< Foo>
。
What I need to achieve is in by letting the VariadicTemplate
class do perform some type checking; the variadic template should check in some iterative form that all the arguments received should be let say of the type <Foo>
.
我已经看到类似的地方,但现在我不知道它在哪里:P
I have seen something similar somewhere but now I can not recognize where it was :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
:
But something tells me you want to know if the arguments are all specializations of a class template 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;
}
这篇关于检查可变模板声明中的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文