仅编译时CRC32用户文字 [英] Compile-time only CRC32 user literal

查看:61
本文介绍了仅编译时CRC32用户文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法正常工作,我的大脑正在融化.该代码看起来应该可以工作.我希望该函数仅在编译时起作用,而不生成任何运行时代码或可调用函数.

Can't get this to work and my brain is melting. The code looks like it should work. I want the function to only work at compile-time and not generate any runtime code or a callable function.

template< char... str >
constexpr uint32_t operator "" _crc( )
{
    constexpr auto lambda = [ ]( auto l,
                                 uint32_t crc,
                                 auto first,
                                 auto ... lstr )
    {
        if constexpr ( sizeof...( lstr ) == 0 )
            return ~crc;

        return l( l,
                  uCRCTable[ ( crc ^ first ) & 0xFF ] ^ crc >> 8,
                  lstr... );
    };
    return lambda( lambda,
                   uCRCTable[ 0 ],
                   str... );
}

static_assert( 0xC213271D == "stack overflow"_crc );

推荐答案

基于此评论...

@RemyLebeau抱歉,需要澄清一下:我需要它根据参数返回不同的类型.这将为类参数返回字符串的crc32

@RemyLebeau sorry, to clarify: i need it to return a different type depending on the parameters. this returns a crc32 of the string for a class parameter

如该注释线程中所述,无法以标准兼容的方式(通过C ++ 17)进行操作.

As noted in that comment thread, there is no way to do that in a standard compliant way (through the C++17).

如果可以使用clang或gcc,则可以使用gcc扩展名,因为两者都支持它.除非明确提及,否则我常常会忘记MSVC-我没有真正使用过基于Windows的操作系统,因为它们已从Windows 3迁移到Windows ME.

If you can use either clang or gcc, then you can use the gcc extension as both support it. I often forget about MSVC unless it is explicitly mentioned - I've not really used a windows-based OS since they went from Windows 3 to Windows ME.

但是,由于您的crc函数是constexpr,因此您可以将crc值映射到唯一类型.

However, since your crc function is constexpr, you can map the crc value to a unique type.

constexpr std::uint32_t
operator""_crc(char const * str, std::size_t len)
{
    // implementation to compute the value
}

template <auto Val>
struct CRC
: std::integral_constant<decltype(Val), Val>
{ };

// example...
constexpr auto zzz = CRC<"zzz"_crc>{};

对于从某些字符串" _crc返回的每个唯一值,您将获得唯一类型.

You will get a unique type for each unique value returned from "some string"_crc.

这不是很好,但是您可能无法使用编译器更接近字符串文字.

It's not as nice, but you may not get much closer to what you want with string literals using your compiler.

在您承诺使用32位CRC之前,请看看这里,看看有没有发生冲突的机会(例如,使用不同的字符串产生相同的哈希),并确保您对此感到满意.

Before you commit to using a 32-bit CRC, look here to see the chance of getting a collision (e.g., producing the same hash with different strings) and make sure you are comfortable with it.

这篇关于仅编译时CRC32用户文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆