我想根据模板 bool 参数有条件地在函数中声明局部变量。因此,如果这是真的,它应该在那里,否则不应该在那里,因为我不希望该变量在堆栈上分配内存或调用其构造函数。它也可以是基本类型。
我无法在 constexpr if 块中声明它,因为我需要用法之间的持久性。
-
我可以声明变量并添加[[maybe_unused]]
。那么,是否有编译器优化保证不为变量分配内存呢?
template <bool T> void foo()
{
[[maybe_unused]] SomeLargeClass x;
if constexpr(T)
{
/* ... do something with x */
}
/* ... do something without x */
if constexpr(T)
{
/* ... do something more with x */
}
}
-
我尝试将声明替换为
std::enable_if_t<T, SomeLargeClass> x;
但它不起作用,因为T==false
case 无法提供类型。为什么这不是SFINAE?
-
我还有其他选择吗?
假设规则可能会丢弃未使用的SomeLargeClass
,但如果该类进行分配,情况会更复杂。
一种简单的权衡是使用std::conditional
并有SomeLargeClass
需要时,以及其他情况下的一些虚拟小班;
struct Dummy
{
// To be compatible with possible constructor of SomeLargeClass
template <typename ...Ts> Dummy(Ts&&...) {}
};
template <bool B> void foo()
{
[[maybe_unused]] std::conditional_t<B, SomeLargeClass, Dummy> x;
if constexpr(B) {
// ... do something with x
}
// ... do something without x
if constexpr(B) {
// ... do something more with x
}
}
作为替代方案,您可以重写您的函数,使您的类仅位于 constexpr 块中:
template <bool B> void foo()
{
const auto do_something_without_x = [](){
// ... do something without x
};
if constexpr(B) {
SomeLargeClass x;
// ... do something with x
do_something_without_x();
// ... do something more with x
} else {
do_something_without_x();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)