[英]Unify type and non-type template parameters
我有一个类型特征,检查给定类型是否是给定类模板的实例:
template <template <typename...> class C, typename T>
struct check_is_instance_of : std::false_type { };
template <template <typename...> class C, typename ...Ts>
struct check_is_instance_of<C, C<Ts...>> : std::true_type { };
template <template <typename...> class C, typename T>
struct is_instance_of : check_is_instance_of<C, std::remove_cv_t<T>> { };
不幸的是,这不适用于非类型模板参数,因为它们不会被可变参数模板参数“捕获”,因此
is_instance_of<std::integral_constant, std::true_type>
产生编译错误。 有没有办法编写适用于任意数量的类型和非类型模板参数的is_instance_of
实现?
除非非类型参数都是相同类型并且您知道它是哪种类型, 否则我认为没有一种干净的方法可以做到这一点。 在这种非常特殊的情况下,可以使用函数重载。
在任何其他情况下,您最终都会遇到完美转发问题的模板参数版本,您必须专门针对每个类型/非类型参数组合。
如果您只需要处理同类非模板参数并且您可以猜测类型,则以下内容应该有效。 您可以为不同的类型重载instance_of(这里只介绍了int),但是您必须为您希望能够处理的每种类型显式创建一个实例:
// variation for non-type parameters, only for uniform parameters with
// known type.
template <typename V, template <V...> class C, typename T>
struct check_is_instance_of_nontype : std::false_type { };
template <typename V, template <V...> class C, V... Values>
struct check_is_instance_of_nontype<V, C, C<Values...>> : std::true_type { };
// this is as in your example
template <template <typename...> class C, typename T>
struct check_is_instance_of : std::false_type { };
template <template <typename...> class C, typename ...Ts>
struct check_is_instance_of<C, C<Ts...>> : std::true_type { };
template <template <typename...> class C, typename T>
struct is_instance_of : check_is_instance_of<C, std::remove_cv_t<T>> { };
template <template <typename...> class C, typename T>
constexpr bool instance_of()
{
return is_instance_of< C, T>::value;
}
template <template <int...> class C, typename T>
constexpr bool instance_of()
{
return check_is_instance_of_nontype< int, C, T>::value;
}
template< int... >
struct Duck
{
};
template<typename A, typename B>
struct Swallow
{
};
int main() {
typedef Duck<1, 2> SittingDuck;
typedef Swallow< int, int> UnladenSwallow;
std::cout << instance_of< Duck, SittingDuck>() << instance_of< Swallow, UnladenSwallow>();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.