title: How to design a function with an optional random seed argument to be passed to mt19937
body: <p>In R I can build the following <code>roll_die(seed = NULL)</code> function that returns a random integer between 1 and 6, and it allows <strong>the option</strong> of specifying a seed for the RNG.</p>
  
  <pre><code>roll_die_r &lt;- function(seed = NULL){
    # Returns a random number between 1 and 6
    # Optionally specify a RNG seed
  
    set.seed(seed)
    return(sample(x = 1:6, size = 1L))
  }
  </code></pre>
  
  <p>This is nice because I can call it with the default <code>seed = NULL</code> and get back a random value <em>or</em> I can call it with a specified seed value so that I can get reproducible results.</p>
  
  <pre><code>roll_die_r()  # random
  roll_die_r(seed = 0)  # always returns 6
  </code></pre>
  
  <p>How do I implement the same thing in c++ using <a href="http://www.cplusplus.com/reference/random/mt19937/" rel="nofollow noreferrer">mt19937</a>? The best I can come up with is </p>
  
  <pre><code>#include &lt;Rcpp.h&gt;
  #include &lt;random&gt;
  using namespace Rcpp;
  
  // [[Rcpp::plugins(cpp11)]]
  
  // [[Rcpp::export]]
  int roll_die_cpp(int seed = -1){
    // Returns a random integer between 1 and 6
    // Optionally specify a RNG seed
  
    std::mt19937 mt;
  
    // Seed the RNG
    if(seed == -1) seed = std::random_device{}();
    mt.seed(seed);
  
    std::uniform_int_distribution&lt;int&gt; dist(1, 6);
    int result = dist(mt);
    return result;
  }
  </code></pre>
  
  <p>But this is not ideal because the user might accidentally <code>call roll_die_cpp(seed = -1)</code> and expect to get back a reproducible result which is not the case.</p>
  
  <pre><code>roll_die_cpp()  # random
  roll_die_cpp(seed = 0)  # always returns 5
  roll_die_cpp(seed = -1)  # random
  </code></pre>
  
  <p>My question is not specifically about the <code>roll_die()</code> method or random number generators - it's more about the function design. In R I often use functions with default parameters set to NULL but I don't know how to accomplish the same thing in c++.</p>
  
  <p>UPDATE:
  Here's another example of what I'm getting at.</p>
  
  <p>R function</p>
  
  <pre><code>return_0 &lt;- function(msg = NULL){
    if(!is.null(msg)) print(msg)
    return(0L)
  }
  return_0()  # doesn't print a message
  return_0("hello world")  # prints hello world
  </code></pre>
  
  <p>cpp function</p>
  
  <pre><code>// [[Rcpp::export]]
  int return_0_cpp(std::string msg = "don't print"){
    if(msg != "don't print") Rcpp::Rcout &lt;&lt; msg;
    return(0);
  }
  
  return_0_cpp()  # doesn't print a message
  return_0_cpp(msg = "hello world")  # prints hello world
  return_0_cpp(msg = "don't print")  # doesn't print a message
  </code></pre>
  
  <p>Notice how awkward <code>return_0_cpp()</code> is. What's a clean way of doing in cpp what I've created in R?</p>