r/cpp • • Dec 08 '18

A better C++ dice roller class

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

17 comments sorted by

7

u/CaptainCrowbar Dec 08 '18

A few days ago someone posted some dice rolling code, with which most of us weren't impressed. Instead of complaining about it I decided to make something better. This is a flexible dice roller implemented as a random number distribution (as in <random>); you can build a set of dice either from its component parts or by parsing a string. As a bonus, I also included a simple rational number class (needed to support dice arithmetic that returns a fractional result).

Example:

auto dice = Dice(2, 10) * 5 + Dice(3, 6) + 10;
dice = Dice("2d10x5 + 3d6 + 10"); // same thing
std::minstd_rand rng(42);
std::cout << dice(rng) << "\n";

12

u/STL MSVC STL Dev Dec 08 '18

UDLs for 2_d10 and 3_d6 would be cool.

4

u/CaptainCrowbar Dec 08 '18

Good idea! I've just added them.

2

u/meneldal2 Dec 10 '18

It's nice, but one thing that is quite common is to roll for successes or to have exploding dice.

It would be possible to implement this by passing some lambda as an additional parameter. It would be called after each roll, and its return value would be used instead of the basic return.

For example:

auto explodingDice = Dice(1,10,1,
     [](int roll, Dice* this){ return roll==10?this->operator()+roll: roll;} //rolls again and adds the result recursively if roll returns 10.
);

auto successDice = Dice(1,6,1,
    [](int roll, Dice* this){ return roll>4?1:0;} //1 for success, 0 for failure
);

You can also add syntax for the string parsing, but allowing arbitrary processing functions would be awesome, it would actually make it superior to Roll20 in some cases (though this interface is limited because you can't do things like reroll once or keep n among m dice), so I guess you'd need a different interface.

1

u/LKummer Dec 08 '18 edited Dec 08 '18

Isn't the use of string_view causing undefined behavior? For example in the example code:

auto dice2 = Dice("2d10x5 + 3d6 + 10");

Since the string passed is a rvalue temporary, it's getting destructed before the string_view is accessed. So it's accessing a dangling pointer?

Same with line 10 in Dice.cpp? (I also think the static here doesn't actually do anything since it's getting destructed when the lambda finishes executing? Am I wrong? )

static constexpr std::string_view whitespace = "\t\n\f\r ";

I'd love if someone with more experience than me would pitch it, I usually avoid string_view because of these dangling "issues", only using it in later stages as an optimization.

Sneaky edit: I was wrong, this is not undefined behavior, thanks for /u/Wurstinator for pointing it out.

Since you're using MSVC I'd also replace strtoll to from_chars just for the hell of it. this blog post was posted here recently, which introduced me to it and it looks pretty neat.

7

u/Chippiewall Dec 08 '18

To add to what the others said, even if the literal were a temporary it wouldn't matter. The string view is converted in the constructor of Dice and a temporary isn't destructed until the end of the expression in which it's used (i.e. when Dice's constructor returns - not when the string_view's constructor returns).

It's a fairly pointless use of string_view anyway as the first use of it is to convert it into a std::string.

5

u/Wurstinator Dec 08 '18

0

u/LKummer Dec 08 '18 edited Dec 08 '18

You're right, I got the terminology wrong, was thinking temporary in my head.

Aren't they still temporary though? Getting destructed before the string_view is accessed?

1

u/Wurstinator Dec 08 '18

A string literal is a pointer, so it's the same as passing e.g. the literal 1 to a function. The constructor takes that pointer by value, so it's simply copied and remains alive for the call of the function.

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?

6

u/STL MSVC STL Dev Dec 08 '18

sizeof and decltype can observe the difference. A reference to an array can bind to a string literal, but it can't bind to a pointer.

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.

2

u/LKummer Dec 08 '18 edited Dec 08 '18

Oh! You're absolutely right. It's also mentioned in the notes on the cppreference page. I didn't realize the lifetime of string literals worked like this (though it makes perfect sense with them being char arrays), thank you for pointing out my mistake and teaching me something.

I'd still argue against using string_view in both cases, safety in the constructor and short string optimization in both. Though these arguments are subjective and you're completely correct about it not being undefined behavior, so the use of string_view here is not wrong.