本文介绍了什么是改写这个泛型函数我用C在C写++的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//Prints out a given array 
template <typename T>
void print(T t)
{
    for(int i = 0; i < t.size(); i++)
    {
        cout << t[i] << " ";
    }
    cout << endl;
}

我有一个想法,但它包含传递数组的大小。是否有可能避免这种情况?

I have an idea but it includes passing the size of the array. Is it possible to avoid this?

*更新
感谢所有的答案/想法,但这个问题是越来越方式深度超过我的呼吸管可以处理。我想重写我的C ++ code在C,因为它是可怕的书面和缓慢。我现在明白,我有一个机会,使其即使在糟糕的C.我会从在Python根本上改写(性能被定罪)。再次感谢

*UpdateThanks for all of the answers/ideas but this problem is getting way deeper than my snorkeler can handle. I wanted to rewrite my C++ code in C because it was horribly written and slow. I see now that I have an opportunity to make it even worse in C. I'll rewrite it from the ground up in Python(performance be damned). Thanks again

推荐答案

如果你没有的元素,它是

If you don't have ELEMENTS, it's

#define ELEMENTS(a) (sizeof(a)/sizeof(*a))

然后,

#define print_array(a, specifier) print_array_impl(a, specifier, ELEMENTS(a), sizeof(*a))

void print_array_impl(void* a, char* specifier, size_t asize, size_t elsize)
{
    for(int i = 0; i < asize; i++)
    {
        // corrected based on comment -- unfortunately, not as general
        if (strcmp(specifier, "%d") == 0)
           printf(specifier, ((int*)a)[i]); 
        // else if ... // check other specifiers
        printf(" ");
    }
    printf("\n");
}

使用这样

print_array(a, "%d") // if a is a int[]

A 必须是一个数组名,而不是一个指针(或者元素不会工作)

and, a needs to be an array name, not a pointer (or else ELEMENTS won't work)

这篇关于什么是改写这个泛型函数我用C在C写++的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:09