简体   繁体   中英

Declare templated class object when non type argument value to be known at run time : operator + overloading in templated class

I want to create a temp array object with length of array equal to sum of lengths of arr1 and arr2. How do I do it? The following function is declared as friend in class array.

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;
    ........
}

Here size() member function simply returns the length of data. Class declaration is:

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....
};

This should work in main()->

arr3 = arr1 + arr2;

Anybody has any clue as to what can be done? Where is return type resolver significant here?

template non type parameters should be constexpr values.

so you might do

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;
    // ........
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM