是否可以在其成员函数中使用类模板

Is it possible to use a class template in its member functions?

本文关键字:函数 成员 是否      更新时间:2023-10-16

我的类是大小参数化的。在它的一种方法中,我必须创建一个临时数组,但我不知道如何将类的大小模板传递给成员函数。这就是我尝试的方式:

#include <array>
template<unsigned int N>
class MyClass{
    std::array<int,N> m_data;
  public:    
    void myFunc(){
        std::array<int,N> tempArray;
    }
};

int main(){
    MyClass<5> obj;
    obj.myFunc();
}

编辑:构建日志:

C:Windowssystem32cmd.exe /C ""C:/Program Files/mingw-w64/x86_64-6.3.0-win32-seh-rt_v5-rev1/mingw64/bin/mingw32-make.exe" -j6 SHELL=cmd.exe -e -f  Makefile"
"----------Building project:[ hatizsak_konyv - Debug ]----------"
mingw32-make.exe[1]: Entering directory 'E:/progi/c++/CodeLite/Other/algoritmusok/dinamikus_programozas/hatizsak_konyv'
"C:/Program Files/mingw-w64/x86_64-6.3.0-win32-seh-rt_v5-rev1/mingw64/bin/g++.exe"  -c  "E:/progi/c++/CodeLite/Other/algoritmusok/dinamikus_programozas/hatizsak_konyv/main.cpp" -g -O0 -Wall  -o ./Debug/main.cpp.o -I. -I.
E:/progi/c++/CodeLite/Other/algoritmusok/dinamikus_programozas/hatizsak_konyv/main.cpp: In instantiation of 'void MyClass<N>::myFunc() [with unsigned int N = 5u]':
E:/progi/c++/CodeLite/Other/algoritmusok/dinamikus_programozas/hatizsak_konyv/main.cpp:15:16:   required from here
E:/progi/c++/CodeLite/Other/algoritmusok/dinamikus_programozas/hatizsak_konyv/main.cpp:8:27: warning: unused variable 'tempArray' [-Wunused-variable]
         std::array<int,N> tempArray;
                           ^~~~~~~~~
"C:/Program Files/mingw-w64/x86_64-6.3.0-win32-seh-rt_v5-rev1/mingw64/bin/g++.exe" -o ./Debug/hatizsak_konyv @"hatizsak_konyv.txt" -L.
mingw32-make.exe[1]: Leaving directory 'E:/progi/c++/CodeLite/Other/algoritmusok/dinamikus_programozas/hatizsak_konyv'
====1 errors, 1 warnings====

模板参数在模板类的方法中可见;代码是正确的。

完全没有错误,在

提供的代码示例中也没有错误,在构建日志中也没有错误。构建日志中的消息只是一个警告(在为其提供上下文之前带有行(,它会根据命令行上提供的-Wall选项正确警告您未使用该变量的事实。除此之外,代码在 ideone 和我的机器上都可以很好地编译(它给你完全相同的警告,而不是错误(。

[matteo@teolapkubuntu /tmp]$ g++ -Wall -Wextra -std=c++11 stuff.cpp 
stuff.cpp: In instantiation of ‘void MyClass<N>::myFunc() [with unsigned int N = 5u]’:
stuff.cpp:15:16:   required from here
stuff.cpp:8:27: warning: unused variable ‘tempArray’ [-Wunused-variable]
         std::array<int,N> tempArray;
                           ^~~~~~~~~

构建日志末尾的"1 错误"消息只是 CodeLite 误解了编译器输出;有一个关于它的开放错误,其条件与您的类似。