【问题标题】:Declare templated class object when non type argument value to be known at run time : operator + overloading in templated class当在运行时知道非类型参数值时声明模板类对象:模板类中的运算符+重载
【发布时间】:2021-04-10 16:03:17
【问题描述】:

我想创建一个临时数组对象,其数组长度等于 arr1 和 arr2 的长度之和。我该怎么做? 以下函数在类数组中被声明为友元。

template<class T1, int l1>
array<T1, l1> operator +( const array<T1, l1> &arr1, const array<T1, l1> &arr2 )
{
    int add= arr1.size()+ arr2.size();
    array<T1, add> temp;
    ........
}

这里的 size() 成员函数只是简单地返回数据的长度。 类声明是:

template<class T, int length>
class array
{
    T *data{};
 public:
  //Overloaded assignment operator taking arr object as parameter

    template<class T1, int l1>
    array& operator=(const array<T1, l1> &arr_copy);

    template<class T1, int l1>
    friend array<T1, l1> operator +( const array<T1, l1> &arr1, const array<T1, l1> &arr2 );

....Constructors and member functions....
};

这应该可以在 main()->

arr3 = arr1 + arr2;

有人知道可以做什么吗? 返回类型解析器在哪里很重要?

【问题讨论】:

  • 如果值仅在运行时已知,则短答案是 no。模板在编译时解析。
  • 你能建议一种我可以重载 + 运算符以按需要工作的方法吗?
  • 这正在缓慢但肯定会变成XY Problem
  • @PaulMcKenzie 我并不是要专注于某个特定的 Y。我完全陷入了这个问题。如果可以的话,请给我指路
  • 首先,为什么模板化的array 类有T* data?那不应该只是T data[length];吗?这个类看起来很奇怪,因此你应该准确地说明你想用这个array 类完成什么。

标签: c++ templates operator-overloading c++17 c++20


【解决方案1】:

模板非类型参数应该是 constexpr 值。

所以你可能会这样做

template<class T1, int l1>
array<T1, l1 + l1> operator +( const array<T1, l1> &arr1, const array<T1, l1> &arr2 )
{
    constexpr int add = l1 + l1;
    array<T1, add> temp;
    // ........
}

【讨论】:

  • 这里没有定义l2
  • 已修复错字。应该是l1(或为arr2添加l2参数)
  • 你能举个例子如何在这个中添加l2
  • @ShadyD: template&lt;class T1, int l1, int l2&gt; array&lt;T1, l1 + l2&gt; operator +( const array&lt;T1, l1&gt; &amp;arr1, const array&lt;T1, l2&gt; &amp;arr2 ).
猜你喜欢
  • 2018-03-29
  • 2016-05-28
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 2016-04-21
相关资源
最近更新 更多