gpt4 book ai didi

c++ - 如何在编译时判断一个类型是否派生自模板类?

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:05 24 4
gpt4 key购买 nike

假设我有一些模板类:

template<class T>
class Foo{}

template<class T>
class Bar{}

现在,我想确保(在编译时)Bar 中使用的类型派生自 Foo。我已经找到了 this显示如何在运行时执行此操作的答案,但我想在编译时检查,可能使用 static_assert 或其他东西。
有办法做到这一点吗?

最佳答案

Now, I want to make sure (at compiletime) that the type used in Bar is derived from 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 .
基本思想是您可以绑定(bind) T 类型的临时对象。至 const Foo<U> &如果T源自 Foo 的特化, 不管是什么 U .因此,您可以声明(无需定义)几个函数,例如示例中的函数来测试它,然后在 static_assert 中使用声明的返回类型。或任何其他常量上下文。


编辑

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

关于c++ - 如何在编译时判断一个类型是否派生自模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45128391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com