c++ - 通过字符串模板参数访问元组

标签 c++ templates c++11 variadic-templates

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/

相关文章:

javascript - Handlebars 中的宏

c++ - 创建需要指向方法函数的指针的模板谓词类,并随之而来的编译器错误

c++ - Visual C++ 2012 似乎不尊重 lambda 中的默认捕获

c++ - 嵌套绑定(bind)表达式

c++ - Qt Creator - 如何为 ubuntu linux 设置应用程序图标?

c++ - Winsock 总能找到连接

c++ - 包含指针的 vector

c++ - 如何从主项目c++加载DLL

templates - 是否可以将 CSS3 框阴影内联应用于 HTML 电子邮件?

c++ - 使用 STL 在 list<MyStruct> 中查找成员的最小值