static_assert和类模板 [英] static_assert and class templates

查看:115
本文介绍了static_assert和类模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static_assert 功能有问题。当我直接实例化一个类模板时,一切都按预期工作。但是当我将其作为不同类模板的参数传递时, static_assert 不起作用。

I have a problem with the static_assert feature. When I instantiate a class template directly, everything works as expected. But when I pass it as a parameter for the different class template, static_assert does not work.

template <int X>
class A{
    static_assert(X == 0, "X != 0");
};

template <class T>
class B{

};

B<A<1>> b;           // Static assert does not work
A<1>    a;           // error: static assertion failed: X != 0

EDIT

感谢大家的回答。有没有一种方法可以显式实例化A而无需创建A实例/不从A继承?我正在尝试:

Thanks all for the answers. Is there a way to explicitly instantiate A without creation of A instances / inheriting from A? I was trying this:

template <int X>
class A{
    static_assert(X == 0, "X != 0");
};

template <class T>
class B;

template <template <int X> class T, int X>
class B<T<X>>{
    template class T<X>;
};

但这是不正确的。

推荐答案

对于 B< A< 1>> b; A< 1> 仅用作模板参数,不会引起类模板 A 的隐式实例化,然后是<$ c不会触发 A 定义内的$ c> static_assert 。

For B<A<1>> b;, A<1> is only used as template argument, which doesn't cause implicit instantiation of class template A, then the static_assert inside A's definition won't be triggered.


当代码在需要完全定义的类型的上下文中引用模板时,或者当类型的完整性影响代码时,并且尚未显式实例化此特定类型时,将发生隐式实例化。例如,当构造此类型的对象时,而不是在构造指向该类型的指针时。

When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.

,对于 A< 1> a; A <1> 必须是完整类型(构造 a ),然后发生隐式实例化,并触发 static_assert

On the other hand, for A<1> a;, A<1> is required to be a complete type (to construct a), then implicit instantiation happens, static_assert is fired.

EDIT

您可以使用 sizeof (要求类型完整)来引起隐式实例化并触发 static_assert 。例如,

You can use sizeof (which requires the type to be complete) to cause the implicit instantiation and fire the static_assert. e.g.

template <class T>
class B{
    static_assert(sizeof(T) > 0, "static_assert for implicit instantiation");
};

这篇关于static_assert和类模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆