Can this macro be converted to a function?

后端 未结 16 1233
后悔当初
后悔当初 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 17:03

    Yes it can be made a template in C++

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

    to use:

    struct JibbaJabba
    {
       int int1;
       float f;
    };
    
    int main()
    {
        cout << "sizeof JibbaJabba is " << getTypeSize() << 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.

提交回复
热议问题