mercredi 31 mars 2021

Compiler error when creating an object using templated constructor

I am seeing a compiler error when I try to create an object of type 'F'. The constructor takes a std::array as input but something is going wrong with the call to the relevant constructor. The minimal code and compiler output are shown below:

#include <iostream>
#include <array>

using namespace std;


template < class T >
class F
{
    public:
        typedef T* iter;
        typedef const T* const_iter;
        
        F() : s_(0), c_(0) {}
        
        template < unsigned U >
        F( std::array<T, U>& arr ) : begin_(arr.begin()), end_(arr.end()), s_(0), c_(U) {}
        
    private:
        T* begin_;
        T* end_;
        std::size_t s_;
        std::size_t c_;
        
        F( const F& );
        F& operator=( const F& );
};

int main()
{
   cout << "Hello World" << endl; 
   
   std::array<int16_t, 45> arrayTemp;
   F<int16_t> arr1(arrayTemp); //This line causes the error
   
   
   return 0;
}

Compiler output (https://www.tutorialspoint.com/compile_cpp11_online.php, gcc v 7.1.1):

$g++ -std=c++11 -o main *.cpp
main.cpp: In function ‘int main()’:
main.cpp:34:29: error: no matching function for call to ‘F<short int>::F(std::array<short int, 45>&)’
    F<int16_t> arr1(arrayTemp);
                             ^
main.cpp:25:9: note: candidate: F<T>::F(const F<T>&) [with T = short int]
         F( const F& );
         ^
main.cpp:25:9: note:   no known conversion for argument 1 from ‘std::array<short int, 45>’ to ‘const F<short int>&’
main.cpp:17:9: note: candidate: template<unsigned int U> F<T>::F(std::array<T, U>&)
         F( std::array<T, U>& arr ) : begin_(arr.begin()), end_(arr.end()), s_(0), c_(U) {}
         ^
main.cpp:17:9: note:   template argument deduction/substitution failed:
main.cpp:34:29: note:   mismatched types ‘unsigned int’ and ‘long unsigned int’
    F<int16_t> arr1(arrayTemp);
                             ^
main.cpp:14:9: note: candidate: F<T>::F() [with T = short int]
         F() : s_(0), c_(0) {}
         ^
main.cpp:14:9: note:   candidate expects 0 arguments, 1 provided

Aucun commentaire:

Enregistrer un commentaire