Created
January 23, 2017 05:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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