【问题标题】:C++ Templates as arguments for templatesC++ 模板作为模板的参数
【发布时间】:2017-03-05 18:50:00
【问题描述】:

我遇到了以下问题。我有以下模板Number

template<int n>
struct Number
{
    static const int value = n;
};

现在假设我想在编译时添加两个这样的数字。具体来说,我想让以下 sn-p 工作:

//The following code should display 7:
std::cout << Number_add< Number<3>, Number<4> >::value << std::endl;

我尝试了类似的方法,但我的编译器不喜欢它。

template<Number<int> n1, Number<int> n2>
struct Number_add
{
    static const int value = n1::value + n2::value;
}

实现 Number_add 的正确方法是什么?我认为这里可能需要模板模板参数,但我也无法让它工作。非常感谢您的帮助。

【问题讨论】:

  • template&lt;class n1, class n2&gt; struct Number_add
  • 啊,可以了,非常感谢!

标签: c++ templates compile-time template-templates


【解决方案1】:

Number&lt;int&gt; 不能用作non-type template parameter,因为用户定义的类不是允许的类型之一。允许的类型是(转载自cppreference.com):

  • std::nullptr_t(C++11 起);
  • 整体式;
  • 左值引用类型(对象或函数);
  • 指针类型(指向对象或函数);
  • 指向成员类型的指针(指向成员对象或成员函数);
  • 枚举类型。

您可以按照 cmets 中的 n.m 建议进行操作

template<typename n1, typename n2>
struct Number_add
{
    static const int value = n1::value + n2::value;
}

【讨论】:

    【解决方案2】:
    template<int A, int B>
    constexpr Number<A+B>
    operator+(Number<A>, Number<B> ){ return {}; }
    
    template<class Lhs, class Rhs>
    using Number_add=decltype(Lhs{}+Rhs{});
    
    std::cout << Number_add< Number<3>, Number<4> >::value << std::end;
    

    打印 7。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多