[英]How to determine if a type is derived from a template class at compile time?
Say I have some template classes: 说我有一些模板类:
template<class T>
class Foo{}
template<class T>
class Bar{}
Now, I want to make sure (at compile-time) that the type used in Bar
is derived from Foo
. 现在,我想确保(在编译时)
Bar
使用的类型是从Foo
派生的。 I already found this answer that shows how to do it at runtime, but I would like to check at compile-time, maybe using static_assert
or something. 我已经找到了显示如何在运行时执行此操作的答案,但是我想在编译时进行检查,也许使用
static_assert
或其他方法。
Is there a way to do this? 有没有办法做到这一点?
Now, I want to make sure (at compiletime) that the type used in Bar is derived from Foo.
现在,我要确保(在编译时)Bar中使用的类型是从Foo派生的。
You can do something like this: 您可以执行以下操作:
#include<type_traits>
#include<utility>
template<class T>
class Foo{};
template<typename T>
std::true_type test(const Foo<T> &);
std::false_type test(...);
template<class T>
class Bar {
static_assert(decltype(test(std::declval<T>()))::value, "!");
};
struct S: Foo<int> {};
int main() {
Bar<S> ok1;
Bar<Foo<int>> ok2;
// Bar<int> ko;
}
See it on wandbox . 在wandbox上看到它。
The basic idea is that you can bind a temporary of type T
to const Foo<U> &
if T
is derived from a specialization of Foo
, no matter what's U
. 基本思想是,您可以将类型
T
的临时对象绑定到const Foo<U> &
如果T
是从Foo
派生的,那么无论U
是什么。 Therefore you can declare (no definition required) a couple of functions like the ones in the example to test it, then use the declared return type in a static_assert
or any other constant context. 因此,您可以声明(无需定义)几个函数,如示例中的函数进行测试,然后在
static_assert
或任何其他常量上下文中使用声明的返回类型。
Edit 编辑
As suggested by @Quentin in the comments, probably it's worth replacing the reference with a pointer to prevent false positives from conversion constructors and operators. 正如@Quentin在评论中所建议的那样,可能值得用指针替换引用,以防止转换构造函数和运算符产生误报。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.