【发布时间】:2021-01-26 11:55:17
【问题描述】:
在我们当前的代码库中,我们的代码如下所示(这当然是简化版):
#include <map>
#include <string>
#include <iostream>
using namespace std;
// General template function to convert an enum to a string, given a converter-container
// The converter-container is either a map, or a vector/array etc. of pair,
// e.g. something that has enum in .first and string in .second
template<typename Container, typename Index>
string toString(Container&& names, Index&& index, const string& noMatch = "NoMatch")
{
for (auto&& elem : names) {
if (elem.first == index) {
return elem.second;
}
}
return noMatch;
}
// Simple example enum
enum class Color
{
red, green, blue, pink
};
// Example of two converter-container types
constexpr array colors1 = {pair{Color::red, "Red"}, pair{Color::green, "Green"}, pair{Color::blue, "Blue"}};
const map<Color, string> colors2 = {{Color::red, "Red"}, {Color::green, "Green"}, {Color::blue, "Blue"}};
int main()
{
cout << toString(colors1, Color::red) << " " << toString(colors2, Color::blue) << " "
<< toString(colors2, Color::pink) << endl;
}
此代码按预期工作,并打印出“Red Blue NoMatch”
但是,我想重写 toString 函数,使其不返回字符串,而是返回存储在转换容器中的任何类型(例如 string、string_view 或 char*)。
如果没有 noMatch 部分,任务会很简单,只需使用“auto”而不是“string”作为返回类型:
template<typename Container, typename Index>
auto toString(Container&& names, Index&& index)
{
for (auto&& elem : names) {
if (elem.first == index) {
return elem.second;
}
}
return begin(names)->second;
}
这工作并打印出“红蓝红”,但不是我正在寻找的解决方案。我寻找的是一种拥有的方式:
template<typename Container, typename Index>
auto toString(Container&& names, Index&& index, const <returnType>& noMatch = "")
{
for (auto&& elem : names) {
if (elem.first == index) {
return elem.second;
}
}
return noMatch;
}
但正如你所见,我需要为
FWIW,我们目前使用启用了 c++17 的 gcc 9.2。
谢谢。
【问题讨论】:
-
无论返回类型是什么,它在所有分支中都必须相同。在你的情况下它是 decltype(declval<:value_type>().second).