C++ Templates: Convincing self against code bloat

前端 未结 7 1069
暖寄归人
暖寄归人 2020-12-09 18:08

I have heard about code bloats in context of C++ templates. I know that is not the case with modern C++ compilers. But, I want to construct an example and convince myself.

7条回答
  •  旧时难觅i
    2020-12-09 18:54

    One test would be to put a static variable in data(), and increment it on each call, and report it.

    If MyArray::data() is occupying the same code space, then you should see it report 1 and then 2.

    If not, you should just see 1.

    I ran it, and got 1 then 2, indicating that it was running from the same set of code. To verify this was indeed true, I created another array with size parameter of 50, and it kicked out 1.

    Full code (with a couple tweaks and fixes) is below:

    Array.hpp:

    #ifndef ARRAY_HPP
    #define ARRAY_HPP
    #include 
    #include 
    
    using std::size_t;
    
    template< typename T, size_t N >
    class Array {
      public:
        T * data();
      private:
        T elems_[ N ];
    };
    
    template< typename T, size_t N >
    T * Array::data() {
        static int i = 0;
        std::cout << ++i << std::endl;
        return elems_;
    }
    
    #endif
    

    types.hpp:

    #ifndef TYPES_HPP
    #define TYPES_HPP
    
    #include "Array.hpp"
    
    typedef Array< int, 100 > MyArray;
    typedef Array< int, 50 > MyArray2;
    
    #endif
    

    x.cpp:

    #include "types.hpp"
    
    void x()
    {
        MyArray arrayX;
        arrayX.data();
    }
    

    y.cpp:

    #include "types.hpp"
    
    void y()
    {
        MyArray arrayY;
        arrayY.data();
        MyArray2 arrayY2;
        arrayY2.data();
    }
    

    main.cpp:

    void x();
    void y();
    
    int main()
    {
        x();
        y();
        return 0;
    }
    

提交回复
热议问题