【发布时间】:2013-06-30 23:15:57
【问题描述】:
来自上一个问题:
Doing a static_assert that a template type is another template
Andy Prowl 向我提供了这段代码,让我可以static_assert 一个模板类型是另一种模板类型:
template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of : public std::false_type { };
template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of<TT, TT<Ts...>> : public std::true_type { };
template<typename T>
struct foo {};
template<typename FooType>
struct bar {
static_assert(is_instantiation_of<foo,FooType>::value, ""); //success
};
int main(int,char**)
{
bar<foo<int>> b;
return 0;
}
这很好用。
但这不适用于foo<whatever>的子类:
template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of : public std::false_type { };
template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of<TT, TT<Ts...>> : public std::true_type { };
template<typename T>
struct foo {};
template<typename FooType>
struct bar {
static_assert(is_instantiation_of<foo,FooType>::value, ""); //fail
};
//Added: Subclass of foo<int>
struct foo_sub : foo<int> {
};
int main(int,char**)
{
bar<foo_sub> b; //Changed: Using the subclass
return 0;
}
可以扩展 Andy Prowl 的 is_instantiation_of 代码以允许子类吗?
【问题讨论】:
-
@KerrekSB 这是一个完全不同的问题(但介绍相同)
-
你不能把它做成一个独立的简短问题,比如“是否可以检查一个类是否派生自模板实例”?
-
我的回答似乎也处理了模板别名问题。