Search code examples
c++pointerstemplatesreturn-type

How to differentiate between constructors


I have two constructors in a class template, one with array, one with vector as parameter.

I have pointer members which point to the given parameters.

I have to overload operator[] and write size() method (only one of each) that work with both but I don't know how to differentiate between the given types.

How can I tell which constructor was called?

Thanks in advance.

template<typename T, typename F>
class view {

const T* arrayT;
const std::vector<T>* vectT;
size_t* sizeArray;
F functor{};


view(const T array[], rsize_t sze) {
        arrayT = array; 
        sizeArray = &sze; 
    }

view(const std::vector<T> vect) {
        vectT = &vect;
    }



int size() const{
    if( ?????){
        return sizeArray;
    } else {
        return vecT-> size();
    }
}

T view<T, F>::operator[](int index) const {

     if(????) {
         functor(arrayT[index]);
     } else {
         return functor(vectT->at(index));
     }
}


Solution

  • You can have a private bool flag at class level and set it to true of false based on the constructor being called.

    The Difference can be seen easily as one them takes two parameters and the other takes only one parameter so, constructor calls can be predicted.

    class view {
        bool flag;    
        const T* arrayT;
        const std::vector<T>* vectT;
        size_t* sizeArray;
        F functor{};
    
        /// Accepts two arguments
        view(const T array[], rsize_t sze) {
            flag = true;
            arrayT = array; 
            sizeArray = &sze; 
        }
    
        /// Accepts one argument
        view(const std::vector<T> vect) {
            flag = false;
            vectT = &vect;
        }
    
        int size() const {
            if (flag) {
                return sizeArray;
            } else {
                return vecT-> size();
            }
        }
    
        T view<T, F>::operator[](int index) const {
            if (flag) {
                functor(arrayT[index]);
            } else {
                return functor(vectT->at(index));
            }
        }
    }