简体   繁体   中英

constexpr doesn't seem to work

I'm using Visual Studio 2013 + CTP.

I have defined the following function:

constexpr DWORD const_getHash(const char *str, DWORD curHash = 0) {
    return !*str ? curHash : const_getHash(str + 1, 
        (curHash >> 13 | curHash << (32 - 13)) + (*str >= 'a' ? *str - 32 : *str));
}

which I use like this:

DWORD hash = const_getHash("ok");

The compiler doesn't issue any warnings but by looking at the "disassembly" I can tell that const_getHash() is executed at runtime.

What's wrong?

edit: If I force the function to be executed at compile-time with

constexpr DWORD hash = const_getHash("ok");

the compiler says

Error   1   error C2127: 'hash': illegal initialization of 'constexpr' entity with a non-constant expression

constexpr doesn't force the function to be executed at compile-time. It just tells the compiler that the function can be executed at compile-time if needed.

constexpr functions will be evaluated at compile time when all its arguments are constant expressions and the result is used in a constant expression as well.

(Quoted from the accepted answer here .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM