【问题标题】:How to make a shortcut for a template function instance in c++? [closed]如何在 C++ 中为模板函数实例创建快捷方式? [关闭]
【发布时间】:2020-07-14 19:45:04
【问题描述】:

我想在我的模块(cpp 文件)中使用boost::math::binomial_coefficient<double>。但我不想每次都写所有的噪音,我想给它一个简单的名字binom。但我很难找到一个体面的方法来做到这一点。

#define 肯定会这样做,但建议避免使用宏。

将它包装到我自己的函数中也是一种选择,但它很丑陋,污染了标题,并且有点违背了目的。

我希望我可以使用using 来创建快捷方式,但它无法编译:

using binom = boost::math::binomial_coefficient<double>;
// -> error: expected a type

我知道我可以使用 typedef 为模板类型(类)创建别名,但我不知道如何将其用于函数。

我也尝试将函数分配给变量,但收到警告:

auto binom = boost::math::binomial_coefficient<double>;
// -> warning: no previous extern declaration for non-static variable 'binom'

【问题讨论】:

  • 也许using binom = typename boost::math::binomial_coefficient&lt;double&gt;; ?
  • 好的,这个警告很奇怪。这表明在声明该变量时做了一些可疑的事情。可以发minimal reproducible example吗?
  • typedef 不是解决这个问题的合适方法吗?
  • 分配给变量应该可以工作。我们需要查看更多代码。
  • @IsaacCorbrey,不,不是,因为 binomial_coefficient 不是类型。

标签: c++ function templates alias using


【解决方案1】:

不要使用auto,而是使用const auto 或使用最近的编译器尝试static constexpr auto 或inline constexpr auto。

变量仍然不好,因为它们删除了重载、默认参数,并可能导致不必要的间接。

不幸的是,据我所知,没有好的方法

using binom = boost::math::binomial_coefficient;

差不多了,但不包括&lt;double&gt;

【讨论】:

  • 添加static、const 和constexpr 中的任何一个都会删除警告,谢谢!
猜你喜欢
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2016-05-26
  • 1970-01-01
  • 2013-03-07
  • 2016-11-17
相关资源
最近更新 更多