I am trying to make a compile-time string class. I took a few hints from this post. Unfortunately, I'm stuck on constructor overload precedence: the const char[] constructor is being ignored in favor of the const char* constructor. Any tips would be appreciated!
class string { public: // Can be done compile time. Works lovely! except... template<size_t N> constexpr string(const char(&char_array)[N]) : ptr_(char_array), length_(N-1) {} // This override gets called instead. I *must* keep this constructor. string(const char* const str) : ptr_(str) { length_ = strlen(str); } // Ugly hack. (not acceptable) template<size_t N> constexpr string(const char(&char_array)[N], double unused) : ptr_(char_array), length_(N-1) {} private: const char* ptr_; int length_; }; constexpr const char kConstant[] = "FooBarBaz"; constexpr string kString(kConstant); // Error: constexpr variable 'kString' must be initialized by a constant expression (tries to call wrong overload) constexpr string kString(kConstant, 1.0f); // ugly hack works. There's lots of cool things I can do if I can make compile-time string constants.
- string equality testing is faster on
stringthanconst char * - Eliminate run-time overhead of implicit conversions from
const char *tostringthat callstrlen()on compile-time constant strings. - Compile-time string sets that do equality testing instead of hashing for size < N. (this is multiple cpus of overhead on one application I'm looking at)
std::stringconstructor overloads you will see that they don't even bother with arrays, only pointers.string(const char *)is it problem with compiler? - error: ‘string{((const char*)(& kConstant)), 9}’ is not a constant expression