fork download
  1. namespace NAlignOf
  2. {
  3. template <class TType>
  4. struct TSizeIncrement: TType
  5. {
  6. char Increment;
  7. };
  8.  
  9. template <class TType, unsigned Start, bool Stop>
  10. struct TIncreaseSizeImpl: TIncreaseSizeImpl<TSizeIncrement<TType>, Start,
  11. sizeof(TSizeIncrement<TType>) != Start>
  12. {
  13. };
  14.  
  15. template <class TType, unsigned Start>
  16. struct TIncreaseSizeImpl<TType, Start, true>
  17. {
  18. typedef TType TType_;
  19. };
  20.  
  21. template <class TType>
  22. struct TIncreaseSize: TIncreaseSizeImpl<TType, sizeof(TType), false>
  23. {
  24. };
  25.  
  26. template <class TType>
  27. struct TAlignOf
  28. {
  29. typedef typename TIncreaseSize<TType>::TType_ TIncreased_;
  30. static const unsigned Value_ =
  31. sizeof(typename TIncreaseSize<TIncreased_>::TType_)
  32. - sizeof(TIncreased_);
  33. };
  34. }
  35.  
  36. #include <iostream>
  37.  
  38. struct S0
  39. {
  40. char c;
  41. };
  42.  
  43. struct S1
  44. {
  45. char c;
  46. short s;
  47. };
  48.  
  49. struct S2
  50. {
  51. char c;
  52. int i;
  53. char c2;
  54. };
  55.  
  56. struct S3
  57. {
  58. char c;
  59. char c2;
  60. int i;
  61. };
  62.  
  63. struct S4
  64. {
  65. double d;
  66. };
  67.  
  68. struct S5
  69. {
  70. char c;
  71. long double d;
  72. }__attribute__((packed));
  73.  
  74. int main()
  75. {
  76. std::cout << NAlignOf::TAlignOf<S0>::Value_ << std::endl;
  77. std::cout << NAlignOf::TAlignOf<S1>::Value_ << std::endl;
  78. std::cout << NAlignOf::TAlignOf<S2>::Value_ << std::endl;
  79. std::cout << NAlignOf::TAlignOf<S3>::Value_ << std::endl;
  80. std::cout << NAlignOf::TAlignOf<S4>::Value_ << std::endl;
  81. std::cout << NAlignOf::TAlignOf<S5>::Value_ << std::endl;
  82. }
  83.  
  84.  
Success #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
1
2
4
4
4
1