Skip to content

Instantly share code, notes, and snippets.

@redblobgames
Created January 23, 2017 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redblobgames/de9ad6b44854c7c065e3b397bc5a41ad to your computer and use it in GitHub Desktop.
Save redblobgames/de9ad6b44854c7c065e3b397bc5a41ad to your computer and use it in GitHub Desktop.
C++11 dice rolling syntax: write 2d6 dice roll as 2_d6 c++ syntax
#include <iostream>
#include <cstdlib>
int roll_dice(int numdice, int die) {
int total = 0;
for (int i = 0; i < numdice; i++) {
total += std::rand() % die;
}
return total;
}
// Reference: http://en.cppreference.com/w/cpp/language/user_literal
int operator "" _d4(unsigned long long N) { return roll_dice(N, 4); }
int operator "" _d6(unsigned long long N) { return roll_dice(N, 6); }
int operator "" _d8(unsigned long long N) { return roll_dice(N, 8); }
int main() {
std::srand(std::time(0));
std::cout << "2d6 + 3 = " << 2_d6 + 3 << std::endl;
std::cout << "5d4 + 1 = " << 5_d4 + 1 << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment