gpt4 book ai didi

c++ - C++11如何优雅的检测模板类型是否派生自特定的基类?

转载 作者:太空狗 更新时间:2023-10-29 20:34:17 24 4
gpt4 key购买 nike

我有一个模板类 Context。我想限制用户使用从特定类 Base 派生的指定类型(Stratege1 但不是 Stratege2)。

class Base {
public:
virtual void run() = 0;
};
class Stratege1 : public Base {
public:
virtual void run() {
printf("Stratege1 \n");
}
};
class Stratege2 {
public:
virtual void run() {
printf("Stratege2 \n");
}
};
template <typename T> class Context {
public:
void run() {
t.run();
};
private:
T t;
};

如果用户想这样调用可能没问题:

Context<Stratege1> context;
context.run();

但是我不希望用户使用(以避免意外的潜在运行时问题)

Context<Stratege2> context;
context.run();

因为 Stratege2 不是从 Base 类派生的。有什么优雅的方法可以在编译过程中限制这个概念吗?

感谢您的任何建议。

最佳答案

自 C++11 起,您可以 static_assert一些东西,这意味着当编译时检查失败时得到一个很好的编译错误:

#include <type_traits> // is_base_of
template <typename T>
class Context {
static_assert(std::is_base_of<Base, T>::value,
"T must be a derived class of Base in Context<T>.");
public:
void run() {
t.run();
};
private:
T t;
};

例如:

Context<NotBase> c2;
error: static_assert failed "T must be a derived class of Base in Context<T>."
-> static_assert(std::is_base_of<Base, T>::value,
note: in instantiation of template class 'Context<NotBase>' requested here
-> Context<NotBase> c2;

Full program demo

关于c++ - C++11如何优雅的检测模板类型是否派生自特定的基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576164/

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