C++11 static_assert (and functions to be used therein)

强颜欢笑 提交于 2019-12-02 05:24:54

Take a look at the final C++11 draft, section 20.7, particularly the <type_traits> header.

What you are asking is: std::is_base_of<base, derived>::value;

Regarding your question: static_assert can be evaluated whenever the compiler sees fit, but it will usually:

  • In a template: if the expression uses dependent names, in instatiation time; else, in definition time.
  • Out of template: in definition time.

In addition to @rodrigo’s answer (he was faster …),

When is static assert executed? Can I put it anywhere in a template and it is evaluated for each template instanciation? Could it be used to constrain template parameters to be a specific subtype of a class?

Unfortunately, no. For instance, a static_assert(false, "bummer"); is always executed, no matter the template. This in particular fails if you want to (partially) specialise a template.

The standard (§7.4) says:

[If the condition to static_assert is false] the program is ill-formed, and the resulting diagnostic message (1.4) shall include the text of the string-literal, […]

Which is unfortunately quite unspecific but this lack of specificity is in fact exactly how static_assert behaves when it’s not dependent on a template type.

You need to make the condition in a static_assert depend on the template argument to bind its execution to the particular template argument.

So the following would fail:

template <typename T>
struct some_type {
    static_assert(false, "T must be a pointer type");
};

template <typename T>
struct some_type<T*> {
    // …
};

Finally, I heartily recommend you read Marthino’s article on More type traits which details this process more, and gives hints on how to solve many trait-related problems elegantly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!