Tim*_*imo 7 c++ inheritance templates
更具体地说,假设我有一个带参数的类模板A
和B
,我想有一个编译器错误(当模板被实例化)如果B未从A派生
template<class A, class B>
class Foo
{
// static_assert(B is derived from A)
};
Run Code Online (Sandbox Code Playgroud)
Ben*_*igt 10
之前已经问了很多次,但是这很简单我会再次发布解决方案:
~Foo()
{
A* p = (B*)0; // B is required to be a subtype of A
}
Run Code Online (Sandbox Code Playgroud)
检查boost :: is_base_of.如果你想自己动手尝试从Alexyey的代码这个问题:
typedef char (&yes)[1];
typedef char (&no)[2];
template <typename B, typename D>
struct Host
{
operator B*() const;
operator D*();
};
template <typename B, typename D>
struct is_base_of
{
template <typename T>
static yes check(D*, T);
static no check(B*, int);
static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes);
};
Run Code Online (Sandbox Code Playgroud)
编辑.编写静态断言并不是什么大问题,但这里是:
#define STATIC_ASSERT(expr, msg) \
{ stat_assert<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }
template<int>
struct stat_assert;
template<>
struct stat_assert<true>{};
Run Code Online (Sandbox Code Playgroud)
EDIT2.如果你不知道如何合并这些东西,整个工作的事情:ideone上的代码
归档时间: |
|
查看次数: |
5619 次 |
最近记录: |