Background:
I found this handy random number generator and wanted to make a header file for it: http://www.cplusplus.com/reference/random/
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
auto dice = std::bind ( distribution, generator );
int wisdom = dice()+dice()+dice();
However, in C++11, a function declaration with return type ‘auto’ requires a trailing return type so the compiler can decide what the type is. E.g.:
auto foo(int a, int b) -> decltype(a*b);
Problem:
It appears like my header would need to be almost as long as the function itself to determine the type:
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
auto roll() -> decltype(distribution(generator));
Question:
Is there a way around determining the full return type for a function declaration (in a header) that uses the ‘auto’ type? If not, what should my dice() header look like?
Since you use int
as the template type for std::uniform_int_distribution
, the return type of distribution(generator)
is int
. Unless the real code is templated as well, then the return type could be hard-coded to int
.
And if the real code is templated then you can use the result_type
member of std::uniform_int_distribution
:
template<typename T>
typename std::uniform_int_distribution<T>::result_type roll();
Or simply the template type itself:
template<typename T>
T roll();