如何使is_pod< T>测试在编译期间执行而不是执行? [英] How can I make is_pod<T> tests be performed during compilation and not execution?
问题描述
这可能是一个简单的问题,我根本不掌握C ++ 11模板。
This might be an easy question, I don't master C++11 templates at all.
我有一个通用的向量类,不是 std :: vector< T>
出于性能原因(非常具体的代码)。
I have a generic vector class that is not std::vector<T>
for performance reasons (very specific code).
$ c> T 是一个POD或不是,当它是,执行特殊的计算,效率要高于:
I have observed that checking whether T
is a POD or not and, when it is, perform special computations, is much more efficient than not :
void vec<T>::clear() {
if (!std::is_pod<T>::value) {
for (int i = 0; i < size; i++) {
data[i].~T();
}
}
size = 0;
}
这里,我不调用 T
每个项目( size
可以真的巨大),性能真的提高了。但是,一旦模板被编译,测试 if(!std :: is_pod< T> :: value)
是无用的:而不是编译成:
Here, I don't call the destructor of T
for each item (size
can be really huge) and performance is really boosted. But the test if (!std::is_pod<T>::value)
is useless once the template was compiled : rather than being compiled to :
void vec<int>::clear() {
if (false) {
for (int i = 0; i < size; i++) {
data[i].~int();
}
}
size = 0;
}
我想将它编译成:
I want it to be compiled to :
void vec<int>::clear() {
size = 0;
}
编译器聪明足以跳过 if (false)
阻止或 if(true)
测试?
Is the compiler "clever" enough to skip if (false)
blocks or if (true)
tests ? Do I have to write that code somewhat differently ?
推荐答案
编译器是否聪明跳过if(false)块或if(true)测试?
Is the compiler "clever" enough to skip if (false) blocks or if (true) tests?
死代码清除是一种常规执行的简单优化。它的存在对于使许多调试库有效地工作(=在发布模式下没有运行时开销)也至关重要。
Yes, definitely. Dead code elimination is a trivial optimisation that is performed routinely. Its existence is also crucial to make many debugging libraries work efficiently (= without runtime overhead in release mode).
但是我可能还会重写这个,通过重载基于 is_pod
的函数,可以看到读取器这是一个编译时间区别:
But I would probably still rewrite this to make it visible to the reader that this is a compile-time distinction, by overloading the function based on is_pod
:
void vec<T>::do_clear(std::true_type) { }
void vec<T>::do_clear(std::false_type) {
for (int i = 0; i < size; i++) {
data[i].~T();
}
}
void vec<T>::clear() {
do_clear(std::is_trivially_destructible<T>());
size = 0;
}
在上面的代码中,我使用 is_trivially_destructible
而不是 is_pod
以使代码更加不言自明,正如Nicol在评论中所建议的。这种技术通常在标准库实现和其他库中使用。它被称为 标签分派 。
这篇关于如何使is_pod< T>测试在编译期间执行而不是执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!