模板化静态成员函数在C++中

mmm*_*mmm 4 c++ templates static-methods

我编写了一个简单的测试程序,试图学习如何在C++中使用模板静态成员函数.代码编译,但不能正常工作(打印出一些垃圾).我想我正在使用正确的语法.我已经读过这个或者这个和其他一些东西,但仍然不知道我做错了什么.代码如下:

#include <iostream>
using namespace std;

class Util {
public:
    Util();
    virtual ~Util();

    template <typename T> static void printTab(T tab[]);
};

template <typename T>
void Util::printTab(T tab[]) {
    for (unsigned int i=0; i<sizeof(tab)/sizeof(tab[0]); i++) {
        cout << tab[0] << " ";
    }
    cout << endl;
}

int main() {

    float tabFloat[5] {1, 2, 3, 4, 5};
    unsigned char tabChar[3] {1, 2, 3};

    Util::printTab(tabFloat);
    Util::printTab(tabChar);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

任何提示赞赏.

BЈо*_*вић 5

您需要将大小作为另一个模板参数传递:

#include <iostream>
using namespace std;

class Util {
public:
    Util();
    virtual ~Util();

    template <typename T,int N> static void printTab(T (&tab)[N])
    {
        for (int i=0; i<N; i++) {
            cout << tab[i] << " ";
        }
        cout << endl;
    }
};

int main() {

    float tabFloat[5] {1, 2, 3, 4, 5};
    unsigned char tabChar[3] {1, 2, 3};

    Util::printTab(tabFloat);
    Util::printTab(tabChar);
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

216 次

最近记录:

13 年,11 月 前