C++ 11 中的标准元组允许通过整数模板参数进行访问,如下所示:
tuple<int, double> test;
test.get<1>();
但是如果我想通过字符串模板参数获取访问权限:
test.get<"first">()
我该如何实现?
最佳答案
您可以创建自定义 constexpr 转换函数。我只是想表明 OP 想要的东西(几乎)是可能的。
#include <tuple>
#include <cstring>
constexpr size_t my_cast(const char * text)
{
return !std::strcmp(text, "first") ? 1 :
!std::strcmp(text, "second") ? 2 :
!std::strcmp(text, "third") ? 3 :
!std::strcmp(text, "fourth") ? 4 :
5;
}
int main()
{
std::tuple<int, double> test;
std::get<my_cast("first")>(test);
return 0;
}
这可以在 GCC 4.9.2 中用 C++11 (C++14) 编译。不在 Visual Studio 2015 中编译。
关于c++ - 通过字符串模板参数访问元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779549/