我将编写一个模板来生成随机数据的向量.问题是
std::uniform_int_distribution只接受整数类型,std::uniform_real_distribution对于float类型.我想两者结合起来.这是我的代码.
#include <vector>
#include <random>
#include <algorithm>
#include <iterator>
#include <functional>
template<typename T>
std::vector<T> generate_vector(size_t N, T lower = T(0), T higher = T(99)) {
// Specify the engine and distribution.
if constexpr (std::is_integral<T>) {
std::uniform_int_distribution<T> distribution(lower, higher);
}
else if constexpr (std::is_floating_point<T>) {
std::uniform_real_distribution<T> distribution(lower, higher);
}
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
std::vector<T> vec(N);
std::generate(vec.begin(), vec.end(), generator);
return vec;
Run Code Online (Sandbox Code Playgroud)
我很困惑如何在条件下实现语句.整数类型应包括:short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.浮动类型包括float, double, or long double.
任何帮助建议?
在pre-C++ 17编译器中,您可以使用模板特化来实现if- else逻辑.
// Declare a class template
template <bool is_integral, typename T> struct uniform_distribution_selector;
// Specialize for true
template <typename T> struct uniform_distribution_selector<true, T>
{
using type = typename std::uniform_int_distribution<T>;
};
// Specialize for false
template <typename T> struct uniform_distribution_selector<false, T>
{
using type = typename std::uniform_real_distribution<T>;
};
template<typename T>
std::vector<T> generate_vector(size_t N, T lower = T(0), T higher = T(99))
{
// Select the appropriate distribution type.
using uniform_distribution_type = typename uniform_distribution_selector<std::is_integral<T>::value, T>::type;
uniform_distribution_type distribution(lower, higher);
std::mt19937 engine;
auto generator = std::bind(distribution, engine);
std::vector<T> vec(N);
std::generate(vec.begin(), vec.end(), generator);
return vec;
}
Run Code Online (Sandbox Code Playgroud)
正如Justin在他的评论中指出的那样if constexpr,以以下方式使用块非常简单:
#include <type_traits>
if constexpr (std::is_integral_v<T>) { // constexpr only necessary on first statement
...
} else if (std::is_floating_point_v<T>) { // automatically constexpr
...
}
Run Code Online (Sandbox Code Playgroud)
这仅适用于C ++ 17。有关编译时类型信息的更多信息,请参见C ++参考:
if constexpr (自C ++ 17起)
<type_traits> (自C ++ 11起)
constexpr 说明符(自C ++ 11起)
一般的常量表达式。
| 归档时间: |
|
| 查看次数: |
1019 次 |
| 最近记录: |