Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constructors for literal strings and common strings

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading