Can this macro be converted to a function?

后端 未结 16 1205
后悔当初
后悔当初 2020-12-05 16:27

While refactoring code and ridding myself of all those #defines that we\'re now taught to hate, I came across this beauty used to calculate the number of elements in a struc

相关标签:
16条回答
  • 2020-12-05 16:58

    Answered in detail here: Array Size determination Part 1 and here: Array Size determination Part 2.

    0 讨论(0)
  • 2020-12-05 17:00
    • function, no template function, yes
    • template, I think so (but C++
    • templates are not my thing)

    Edit: From Doug's code

    template <typename T>
    uint32_t StructSize()  // This might get inlined to a constant at compile time
    {
       return sizeof(T)/sizeof(*T);
    }
    
    // or to get it at compile time for shure
    
    class StructSize<typename T>
    {
       enum { result = sizeof(T)/sizeof(*T) };
    }
    

    I've been told that the 2nd one doesn't work. OTOH something like it should be workable, I just don't use C++ enough to fix it.

    A page on C++ (and D) templates for compile time stuff

    0 讨论(0)
  • 2020-12-05 17:01

    xtofl has the right answer for finding an array size. No macro or template should be necessary for finding the size of a struct, since sizeof() should do nicely.

    I agree the preprocessor is evil, but there are occasions where it is the least evil of the alternatives.

    0 讨论(0)
  • 2020-12-05 17:03

    Yes it can be made a template in C++

    template <typename T>
    size_t getTypeSize()
    {
       return sizeof(T)/sizeof(*T);
    }
    

    to use:

    struct JibbaJabba
    {
       int int1;
       float f;
    };
    
    int main()
    {
        cout << "sizeof JibbaJabba is " << getTypeSize<JibbaJabba>() << std::endl;
        return 0;
    }
    

    See BCS's post above or below about a cool way to do this with a class at compile time using some light template metaprogramming.

    0 讨论(0)
  • 2020-12-05 17:07

    Windows specific:

    There is the macro _countof() supplied by the CRT exactly for this purpose.

    A link to the doc at MSDN

    0 讨论(0)
  • 2020-12-05 17:09

    Simplfying @KTC's, since we have the size of the array in the template argument:

    template<typename T, int SIZE>
    int arraySize(const T(&arr)[SIZE])
    {
        return SIZE;
    }
    

    Disadvantage is you will have a copy of this in your binary for every Typename, Size combination.

    0 讨论(0)
提交回复
热议问题