是否可以将static_cast转换为相同类型,从而导致运行时开销? [英] Can static_cast to same type introduce runtime overhead?
问题描述
我有一个采用两种类型(T
和S
)的结构模板,在某些时候使用static_cast
从一种类型转换为另一种类型. T
和S
通常是同一类型.
I have a structure template that takes two types (T
and S
), and at some point uses a static_cast
to convert from one type to the other. It is often the case that T
and S
are the same type.
设置的简化示例:
template <typename T, typename S = T>
struct foo
{
void bar(T val)
{
/* ... */
some_other_function(static_cast<S>(val));
/* ... */
}
};
在S
与T
是同一类的情况下,static_cast
会还是会带来额外的开销,或者它是一个空操作,将始终被忽略?
In the case that S
is the same class as T
, does or can the static_cast
introduce extra overhead, or is it a null operation which will always be ignored?
如果确实增加了开销,是否有一个简单的模板元编程技巧仅在需要时才执行static_cast
,还是我需要创建部分专业化知识来应对T == S
情况?如果可能的话,我宁愿避免整个foo
模板的部分专业化.
If it does introduce overhead, is there a simple template metaprogramming trick to perform the static_cast
only if needed, or will I need to create a partial specialization to cope with the T == S
case? I'd rather avoid the partial specialization of the entire foo
template if possible.
推荐答案
是的,可以.
这里是一个例子:
struct A {
A( A const& ) {
std::cout << "expensive copy\n";
}
};
template<typename T>
void noop( T const& ) {}
template <typename T, typename S = T>
void bar(T val)
{
noop(static_cast<S>(val));
}
template <typename T>
void bar2(T val)
{
noop(val);
}
int main() {
std::cout << "start\n";
A a;
std::cout << "bar2\n";
bar2(a); // one expensive copy
std::cout << "bar\n";
bar(a); // two expensive copies
std::cout << "done";
}
基本上,static_cast
可以导致调用副本构造函数.
basically, a static_cast
can induce a copy constructor to be called.
对于某些类型(例如int
),复制构造函数基本上是免费的,编译器可以消除它.
For some types (like int
), a copy constructor is basically free, and the compiler can eliminate it.
对于其他类型,不能.在这种情况下,复制省略也不合法:如果您的复制构造函数有副作用,或者编译器无法证明它没有副作用(通常,如果复制构造函数很重要),它将被调用.
For other types, it cannot. In this context, copy elision isn't legal either: if your copy constructor has side effects or the compiler cannot prove that it has no side effects (common if the copy constructor is non-trivial), it will be called.
这篇关于是否可以将static_cast转换为相同类型,从而导致运行时开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!