I’m making an Identifier class which is basically an immutable string. It maintains a single constant char array in memory, making it suitable for identifiers which require frequent comparisons.
Here are my constructors.
// Default constructor for Identifier.
Identifier();
// Constructor for Identifier that takes a const char* and its size.
// This constructor is used to create an Identifier from a given string and size.
Identifier(const char* str, uint16_t size);
// Constructor for Identifier that takes a string literals.
// This constructor is used to create an Identifier from a string literals.
template <size_t Len>
Identifier(const char(&str)[Len])
: Identifier(str, Len - 1)
{
std::cout << "template" << std::endl;
}
// Constructor for Identifier that takes a const char*.
Identifier(const char* str);
The method I want to use is like:
// using the template constructor
Identifier id = "identifier";
// using the const char* constructor
const char* str = "Identifier";
Identifier id = str;
However, when I run my test program, it seems that the compiler trend to select the non-template constructor, making the template constructor is never used.
I expect a solution to make the compiler select template constructor first.
>Solution :
Get rid of the template constructor completely, pass by std::string_view (a universal string wrapper) and rely on strlen elision instead. If the compiler sees a string literal, be sure it will be able to determine its length for you (unless this is -O0).
https://godbolt.org/z/qsc3MKTqW