C ++模板函数-多种类型,默认值和...参数?

时间:2019-01-16 11:51:19

标签: c++ c++11 templates

我有几个样板功能,我想用一个模板代替。它们大致如下:

std::vector<double> generate_means(
  std::mt19937& g, unsigned int N,
  double lower = -1.0, double upper = 1.0
) {
  std::uniform_real_distribution<double> dist(lower, upper);
  std::function<double()> rng = std::bind(dist, g);
  std::vector<double> res(N);
  std::generate(std::begin(res), std::end(res), gen);
  return res;
}

需要抽象的元素为返回类型(仅包含类型,始终为vector即可)N之后的参数(例如lowerupper )和分布(例如std::uniform_real_distribution)。

我想大致写些什么:

auto generate_means = generate_template<
  double, // results vector<double>
  std::uniform_real_distribution, // uses uniform distro
  double=-1.0,double=1.0 // with default args
>
auto generate_norm_deviates = generate_template<
  double, // still provides vector<double>
  std::normal_distribution, // different distro
  double=0, double=1.0 // different defaults
>
auto generate_category_ids = generate_template<
  unsigned int,
  std::uniform_int_distribution,
  unsigned int=0, unsigned int // again with two args, but only one default
>

我有一些小件

template <class NUMERIC>
using generator = std::function<NUMERIC()>;

template <class NUMERIC>
std::vector<NUMERIC> series(unsigned int length, generator<NUMERIC> gen) {
  std::vector<NUMERIC> res(length);
  std::generate(std::begin(res), std::end(res), gen);
  return res;
};

但是当我尝试像这样组装时

template <class NUMERIC, class DIST, class...Args>
std::vector<NUMERIC> generator_template(
  std::mt19937& g, unsigned int N,
  Args... args
) {
  DIST<NUMERIC> dist(&args...);
  generator<NUMERIC> gen = std::bind(dist, g);
  return series(N, gen);
} 

我遇到编译错误(在这种情况下为error: expected unqualified-id)。我想要的大约可以实现吗?这种方法是朝正确的方向发展吗,还是我需要做一些根本不同的事情?如果方向正确,我会错过什么?

编辑:

对于应用程序约束:我希望能够使用默认的参数声明生成器,但是我确实需要偶尔使用没有默认值的生成器。没有默认值只是不便,但这并不是致命的。示例:

//... assorted calculations...
auto xmeans = generate_means(rng, 100); // x on (-1,1);
auto ymeans = generate_means(rng, 100); // y on (-1,1);
auto zmeans = generate_means(rng, 100, 0, 1); // z on (0,1);

3 个答案:

答案 0 :(得分:2)

不可能使用浮点数作为模板参数。 但是,您可以执行以下操作:

#include <random>
#include <limits>
#include <algorithm>
#include <vector>
#include <iostream>

template<typename T, template<typename> typename Distribution>
auto generate_random_template(T min = std::numeric_limits<T>::lowest(),
                              T max = std::numeric_limits<T>::max()) {
    return [distribution = Distribution<double>{min, max}]
        (auto &&generator, std::size_t number) mutable {
        std::vector<T> result;
        result.reserve(number);
        auto generate = [&](){return distribution(generator);};
        std::generate_n(std::back_inserter(result), number, generate);
        return result;
    };
}

int main() {
    auto generate_means = generate_random_template<double, std::uniform_real_distribution>(0.0, 1.0);
    std::mt19937 g;
    std::vector<double> randoms = generate_means(g, 10);

    for(auto r : randoms) std::cout << r << std::endl;

    return 0;
}

编辑:出于性能原因,请使用generate_n代替generate

EDIT2:如果您想像使用x,y和z一样使用默认参数,则还可以执行以下操作:

#include <random>
#include <limits>
#include <algorithm>
#include <vector>
#include <iostream>

template<typename T, template<typename> typename Distribution>
auto generate_random_template(T min = std::numeric_limits<T>::lowest(),
                              T max = std::numeric_limits<T>::max()) {
    return [distribution = Distribution<double>{min, max}, min, max]
        (auto &&generator, std::size_t number, auto ...args) mutable {
        std::vector<T> result;
        result.reserve(number);

        if constexpr(sizeof...(args) > 0)
            distribution.param(typename Distribution<T>::param_type(args...));

        else
            distribution.param(typename Distribution<T>::param_type(min, max));

        auto generate = [&](){return distribution(generator);};
        std::generate_n(std::back_inserter(result), number, generate);
        return result;
    };
}

int main() {
    auto generate_means = generate_random_template<double, std::uniform_real_distribution>(-1.0, 1.0);
    std::mt19937 g;
    // x and y are between -1 and 1
    std::vector<double> x = generate_means(g, 10);
    std::vector<double> y = generate_means(g, 10);
    std::vector<double> z = generate_means(g, 10, 0.0, 1.0); // z is between 0 and 1

    for(int i = 0; i < 10; ++i) {
        std::cout << x[i] << "," << y[i] << "," << z[i] << std::endl;   
    }
    return 0;
}

答案 1 :(得分:0)

感谢各式各样的评论者,现在可以正常工作了(将其添加到来自Q的工作区时):

template <class NUMERIC, template<class> class DIST, class ... Args>
std::vector<NUMERIC> generator_template(
  std::mt19937& g, unsigned int N,
  Args &&... args
) {
  DIST<NUMERIC> dist(std::forward<Args>(args)...);
  generator<NUMERIC> gen = std::bind(dist, g);
  return series(N, gen);
};

auto generate_test = generator_template<double, std::uniform_real_distribution, double, double>;

但是,很高兴看到其他答案-仍在尝试一般地理解C ++模板语法,并且希望使用可以让我设置默认参数的版本。

答案 2 :(得分:0)

我很想接受一个构造的分发对象。

template <typename Dist, typename URBG>
std::vector<typename Dist::value_type> generate(Dist&& dist, URBG&& gen, std::size_t N)
{
    std::vector<typename Dist::value_type> res(N);
    std::generate(res.begin(), res.end(), std::bind(std::forward<Dist>(dist), std::forward<URBG>(gen)));
    return res;
}