r/cpp • • Dec 08 '18

A better C++ dice roller class

https://github.com/CaptainCrowbar/dice
1 Upvotes

17 comments sorted by

View all comments

Show parent comments

13

u/STL MSVC STL Dev Dec 08 '18

String literals aren't pointers - they are arrays that can decay to pointers.

1

u/Wurstinator Dec 08 '18

What is the difference in semantics?

5

u/Quincunx271 Author of P2404/P2405 Dec 08 '18

If you pass one to an overload set where one function takes a const char* and the other takes a const char (&)[N], the latter will be selected

5

u/STL MSVC STL Dev Dec 08 '18

That is not true due to the arcane details of how overload resolution works. However, it is possible to observe if you carefully craft your overload set:

C:\Temp\gcc>type meow.cpp
#include <stdio.h>

void meow(const char* ptr) {
    printf("meow(const char* ptr) %s\n", ptr);
}
template <size_t N> void meow(const char (& arr)[N]) {
    printf("meow(const char (& arr)[N]) %s\n", arr);
}

void hiss(const char* const& ptr) {
    printf("hiss(const char* const& ptr) %s\n", ptr);
}
template <size_t N> void hiss(const char (& arr)[N]) {
    printf("hiss(const char (& arr)[N]) %s\n", arr);
}

template <typename CharT> void purr(const CharT* const& ptr) {
    printf("purr(const CharT* const& ptr) %s\n", ptr);
}
template <size_t N> void purr(const char (& arr)[N]) {
    printf("purr(const char (& arr)[N]) %s\n", arr);
}

int main() {
    const char * p = "pointer";
    meow(p);
    meow("string literal");
    hiss(p);
    hiss("string literal");
    purr(p);
    purr("string literal");
}

C:\Temp\gcc>g++ -Wall -Wextra meow.cpp -o meow.exe && meow
meow(const char* ptr) pointer
meow(const char* ptr) string literal
hiss(const char* const& ptr) pointer
hiss(const char* const& ptr) string literal
purr(const CharT* const& ptr) pointer
purr(const char (& arr)[N]) string literal

2

u/Quincunx271 Author of P2404/P2405 Dec 08 '18

Is this special for string literals, or is it true for any array? I completely expected meow("string literal") to output meow(const char (& arr)[N]) string literal.

3

u/STL MSVC STL Dev Dec 09 '18

It’s true for any array. The issue is that overloading values and references can behave unintuitively, even if you know about decay. The hiss() example shows that the template tiebreaker is even involved. This is one of the reasons why I say that overload resolution needs to be treated with care - it works well if you know how to avoid creating complicated scenarios.