将返回类型专用化为 void 或 const 左值引用
specialize return type to void or const lvalue reference
我正在尝试完成以下任务。
enum class Options : uint8_t {
optA,
optB,
optC
};
class Test {
public:
static std::string str;
static std::vector<std::string> vec;
template<Options option>
static auto func()
{
if constexpr (option == Options::optA)
{
return str; // want this to deduce to 'const std::string', but only does so if 'const auto' (const std::string& also fine though)
}
else if constexpr (option == Options::optB)
{
return vec; // want this to deduce to 'const std::vector<std::string>&' but only does so if 'const auto&'
}
// want this to deduce to 'void' but only can if 'auto'
}
}
但是,由于注释的原因,它当然不起作用。
我知道我可以...
1(为每个选项专门化类体外的函数,并特意指定返回类型
或 2( 调用函数时显式传入返回类型
但是有没有更干净的解决方案,我需要做的就是将单个Options
值传递到模板中,其余的在单个函数体中派生?
const std::string& value = Test::func<Options::optA>();
const std::vector<std::string>& values = Test::func<Options::optB>();
Test::func<Options::optC>();
对于非静态func()
,您可以将其标记为const
并使用decltype(auto)
推导:
template<Options option>
decltype(auto) func() const
{
if constexpr (option == Options::optA)
return (str);
else if constexpr (option == Options::optB)
return (vec);
}
str
和vec
都用括号括起来,以便decltype(auto)
推断引用类型。对于optA
,它将返回const std::string&
,对于optB
–const std::vector<std::string>&
,否则void
。
演示 1
对于静态成员函数和静态成员,您可以编写:
template<Options option>
static decltype(auto) func()
{
if constexpr (option == Options::optA)
return std::as_const(str);
else if constexpr (option == Options::optB)
return std::as_const(vec);
}
演示 2
无需返回const std::string
。 您可以只返回一个std::string
,调用方可以决定是否希望它成为常量。 如果你对此感到满意,那么你的函数将成为
template<Options option>
static decltype(auto) func()
{
if constexpr (option == Options::optA)
{
return str;
}
else if constexpr (option == Options::optB)
{
return const_cast<const std::vector<std::string>&>(vec);
}
else //
{ // this bit is not really needed but I like
return; // being explicit that `void` is what we want to return
//
} //
}
现在decltype(auto)
将推断出Options::optA
一个std::string
,Options::optB
一个const std::vector<std::string>&
,Options::optC
,void
。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 对临时对象的Const引用不会延长其生存期
- 对 const 引用参数使用默认值会导致崩溃
- 在运算符重载中使用带有 const 引用的 friend 函数
- C++通过 const 引用传递时不调用派生类函数
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么要返回对小类成员的 const 引用?
- C - 最好将枚举类作为值或const引用
- RVO:返回由值传递的值,即使显式分配给 const 引用也是如此
- const引用与可变成员的对象
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 对类成员而不是 getter 的 Const 引用
- 从类型 'Matrix&' 的右值初始化 类型的非 const 引用无效 'Matrix'
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- STD ::配对的const引用如何工作
- 为什么我的C 函数拒绝返回const引用