问题描述
static_assert
与模板一起似乎是一个非常好的功能.
static_assert
seems to be a very nice feature together with templates.
但是,我无法在标准库中找到用于在编译时进行各种测试的函数.
However, I have trouble finding functions in the standard library for doing various tests at compile time.
例如,我正在寻找一个函数来检查一个类型是否是另一个类型的子类型.boost::is_base_of
可以完成这项工作,但是,它是 std 中的一个类似函数,所以我不需要依赖 boost.
For example, I am looking for a function to check whether a type is a subtype of another one. boost::is_base_of
does the job, however, is a comparable function in std, so I do not need to rely on boost.
基本上,是否有可以在 static_assert
中使用并包含在 C++11 标准库中的函数列表的良好来源?
Basically, is there a good source for a list of functions which can be used in static_assert
and are contained in the standard library of C++11?
static_assert
何时执行?我可以将它放在模板中的任何位置并针对每个模板实例化进行评估吗?是否可以用于将模板参数限制为类的特定子类型?
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?
推荐答案
看看最后的 C++11 草案,第 20.7 节,特别是 标头.
Take a look at the final C++11 draft, section 20.7, particularly the <type_traits>
header.
你要问的是:std::is_base_of::value;
关于您的问题:static_assert
可以在编译器认为合适时进行评估,但通常会:
Regarding your question: static_assert
can be evaluated whenever the compiler sees fit, but it will usually:
- 在模板中:如果表达式使用依赖名称,则在实例化时间;否则,在定义时间内.
- 模板外:定义时间.
这篇关于C++11 static_assert(以及在其中使用的函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!