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

时间:2011-11-27 13:51:52

标签: c++ templates static-methods

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

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

任何提示都表示赞赏。

4 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:2)

sizeof(tab)T*的大小,它不会返回整个数组的大小。你需要将自己作为另一个参数传递给函数。请参阅此处获取解释和其他可能的解决方法:When a function has a specific-size array parameter, why is it replaced with a pointer?

请注意,第二个printTab不会输出可读字符。如果您想看到打印出来的内容,请尝试:

 unsigned char tabChar[3] {'1', '2', '3'};

答案 2 :(得分:1)

如何尝试,您需要在调用函数时发送数组的大小:

#include <iostream>
using namespace std;

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

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

template <typename T>
void Util::printTab(T tab[], size_t sz) {
    for (unsigned int i=0; i<sz; 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, sizeof(tabFloat)/sizeof(float));
    Util::printTab(tabChar, sizeof(tabChar)/sizeof(char));

    return 0;
}

答案 3 :(得分:-1)

我将T的元素数作为函数参数传递或使用STD容器(如Vector)。

您的for循环只打印第一个元素tab[0]而不是tab[i]

您缺少tabFloat和tabChar的初始化=

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

(在我的测试中,我还会使用65,66,67而不是1,2,3来控制台的可读性)

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