微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用模板化构造函数创建对象时编译器错误

如何解决使用模板化构造函数创建对象时编译器错误

当我尝试创建类型为“F”的对象时,我看到编译器错误。构造函数将 std::array 作为输入,但调用相关构造函数时出现问题。最小代码和编译器输出如下所示:

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

编译器输出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,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。