【问题标题】:Can variable templates infer type?变量模板可以推断类型吗?
【发布时间】:2018-02-23 21:23:26
【问题描述】:

介绍了variable templates 所以我可以这样做:

template <typename T>
const auto PI = std::acos(static_cast<T>(-1));

现在,当使用这个变量时,可以推断出类型吗?例如:

const auto TWO_PI = 2.0F * PI;

在这里,我希望PI&lt;float&gt; 似乎编译器应该能够推断出这一点。为什么编译器不会为我选择这个?

【问题讨论】:

  • 为什么要扣浮动?
  • 不知道为什么你认为 PI 应该是浮动的。
  • @Jarod42 因为它乘以 float?
  • 所以编译器应该随机查看子表达式并在可能的情况下选择 something 吗?这种有用的行为怎么样?
  • 好吧,那又怎样?即使我采取您的思路(我仍然不确定编译器如何推断类型),仍然可以将浮点数乘以多种不同的类型。为什么要挑出浮动?然而,这一切都很奇怪。模板变量的模板参数与变量类型之间的所谓关系仍然超出我的理解。

标签: c++14 c++ templates c++14 type-deduction variable-templates


【解决方案1】:

不,这不可能。*


*有一个丑陋的替代方案,但我建议不要使用它:

template <typename T> const auto pi = std::acos(static_cast<T>(-1));

struct auto_pi_t {} auto_pi;

template <typename T> auto operator+(T a, auto_pi_t)
{return a + pi<std::conditional_t<std::is_floating_point_v<T>, T, double>>;}
template <typename T> auto operator+(auto_pi_t, T a)
{return pi<std::conditional_t<std::is_floating_point_v<T>, T, double>> + a;}
// For similar overloads for all plausible operators.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多