繁体   English   中英

如何确定在编译时是否从模板类派生类型?

[英]How to determine if a type is derived from a template class at compile time?

说我有一些模板类:

template<class T>
class Foo{}

template<class T>
class Bar{}

现在,我想确保(在编译时) Bar使用的类型是从Foo派生的。 我已经找到了显示如何在运行时执行此操作的答案,但是我想在编译时进行检查,也许使用static_assert或其他方法。
有没有办法做到这一点?

现在,我要确保(在编译时)Bar中使用的类型是从Foo派生的。

您可以执行以下操作:

#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;
}

wandbox上看到它。
基本思想是,您可以将类型T的临时对象绑定到const Foo<U> &如果T是从Foo派生的,那么无论U是什么。 因此,您可以声明(无需定义)几个函数,如示例中的函数进行测试,然后在static_assert或任何其他常量上下文中使用声明的返回类型。


编辑

正如@Quentin在评论中所建议的那样,可能值得用指针替换引用,以防止转换构造函数和运算符产生误报。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM