Can this macro be converted to a function?

后端 未结 16 1220
后悔当初
后悔当初 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:15

    The type of a template function is inferred automatically, in contrast with that of a template class. You can use it even simpler:

    template< typename T > size_t structsize( const T& t ) { 
      return sizeof( t ) / sizeof( *t ); 
    }
    
    
    int ints[] = { 1,2,3 };
    assert( structsize( ints ) == 3 );
    

    But I do agree it doesn't work for structs: it works for arrays. So I would rather call it Arraysize :)

提交回复
热议问题