c++11:字符串文字的恒定时间查找函数

标签 c++ templates c++11 template-meta-programming

C++ ,可以在编译时通过以下方式生成整数到变量值的恒定时间查找:

template<int>
int *map() {
    static int var = 0;
    return &var;
}

int main() {
    *map<0>() = 42;
    *map<1>() = 1337;

    return *map<0>(); //returns 42
}

注意编译器会创建一个全局变量map<key>::var对于在编译时使用的每个“键”。

是否可以创建一个类似的 map 函数,将字 rune 字用作“键”?请注意,由于字符字面值的本地链接,它们不能用作模板参数。

我需要能够在我的代码的任何部分指定新键,事实上,作为任何表达式的一部分。请注意,在我的整数示例中,我如何指定 map<0>应该只存在于 main() .

注意:特别是,我想使用 __FILE__, __LINE__ 的元组作为键,通过前缀 var 使映射线程特定与 thread_local , 和翻译单元特定的前缀 map()static .因此,理论上,字 rune 字的本地链接不会造成问题。整个事情是记录器的性能优化,它允许为特定文件的部分指定日志级别。

最佳答案

这是一个概念证明,即使我不推荐它 implementation , 请注意,这使用 c++1y 来简化 constexpr :

#include <iostream>

constexpr bool cstrcmp( char const * s1, char const * s2 ) {
    while ( *s2 && *s1 ) {
        if (*s1++ != *s2++ )
            return false;
    }
    return !*s1 && !*s2;
}

constexpr int str_to_val( char const * str ) {
    struct pair { char const*str; int value; };
    constexpr pair const tab[] { {"foo",1}, {"bar", 2} };
    for( auto & e : tab ) {
        if ( cstrcmp(str,e.str) )
            return e.value;
    }
    throw 0;
}

int main() {
    constexpr auto test_0 = str_to_val("foo");
    constexpr auto test_1 = str_to_val("bar");
    //constexpr auto test_2 = str_to_val("baz"); // trigger compilation error
    std::cout << test_0 << " " << test_1 << std::endl;
}

关于c++11:字符串文字的恒定时间查找函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733565/

相关文章:

c++ - 具有嵌套类的模板类

c++ - C++ 标准对超出目标类型范围的类型的强制转换结果有何规定?

c++ - C++错误,编译器无法识别字符串::push_back [closed]

c - 为什么C和C++中signed char的范围不同?

c++ - 找到二进制数中的第一个设置位

c++ - C++ 标准是否要求 C 链接函数为 `noexcept` ?

c++ - 如果我用 extern "C"声明一个函数,我也应该这样定义它吗?

string - SendGrid 使用 template_id 进行字符串替换

C++——系统在哪里存储返回的字符?

c++ - 将函数原型(prototype)发送到模板如何工作?