Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c++ - How can you compare two character strings statically at compile time

I would like to create a macro which can compare 2 strings, and emit a compile time error if the condition isn't met. This could be though of as a compile time assertion.

I'm not sure how I could do this.

For instance:

STATIC_COMPARE("THIS STRING","THIS STRING") -> would emit a compile time error
STATIC_COMPARE("THIS STRING","THIS OTHER STRING) -> wouldn't emit a compile time error.

The macro would look something like

#define STATIC_COMPARE(str1,str2) if (str1==str2) emit an error with a message

So I guess the question boils down to being able to compare the 2 strings at compile time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this with C++11 by using a constexpr function:

constexpr bool strings_equal(char const * a, char const * b) {
    return *a == *b && (*a == '' || strings_equal(a + 1, b + 1));
}

(See a demo)

It's not possible to do this prior to C++11, with the caveat that many compilers will compile equal string literals to be a pointer to the same location. On these compilers it's sufficient to compare the strings directly since they will both be evaluated as equal pointers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...