Template array initialization with a list of values

前端 未结 5 1226
一向
一向 2021-01-14 14:14

In standard c++ we can write :

int myArray[5] = {12, 54, 95, 1, 56};

I would like to write the same thing with a template :



        
相关标签:
5条回答
  • 2021-01-14 14:34

    Yet another solution which doesn't need adder class template. Now you can do this:

    int main() {
    
            Array<int, 10> array;
            array = 1,2,3,4,5,6,7,8,9,10;
            for (size_t i = 0 ; i < array.Size() ; i++ )
               std::cout << array[i] << std::endl;
            return 0;
    }
    

    Output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    Here is the complete solution: http://www.ideone.com/I0L1C

    0 讨论(0)
  • 2021-01-14 14:38

    You're right. This is not possible with current standard C++. However, with the next standard (c++0x) initializer-lists will do just that!

    0 讨论(0)
  • 2021-01-14 14:42

    My solution is to write a class template that accumulates all the values which get passed to the constructor. Here is how you can initizalize your Array now:

    Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
    

    The implementation of adder is shown below with complete demonstration:

    template<typename T>
    struct adder
    {
       std::vector<T> items;
       adder(const T &item) { items.push_back(item); }
       adder& operator,(const T & item) { items.push_back(item); return *this; }
    };
    
    template <class Type, size_t N>
    class Array
    {
    public:
    
        Array(const adder<Type> & init) 
        {
             for ( size_t i = 0 ; i < N ; i++ )
             {
                   if ( i < init.items.size() )
                       m_Array[i] = init.items[i];
             }
        }
        size_t Size() const { return N; }
        Type & operator[](size_t i) { return m_Array[i]; }
        const Type & operator[](size_t i) const { return m_Array[i]; }
    
    private:
    
        Type m_Array[N];
    };
    
    int main() {
    
            Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
            for (size_t i = 0 ; i < array.Size() ; i++ )
               std::cout << array[i] << std::endl;
            return 0;
    }
    

    Output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    See the online demo at ideone yourself : http://www.ideone.com/KEbTR

    0 讨论(0)
  • 2021-01-14 14:44

    This becomes possible in C++0x using initializer lists. Currently, there is no way to do this.

    The closest you can get without this is to use Boost.Assign.

    0 讨论(0)
  • 2021-01-14 14:53

    It's actually very trivial; just remove the constructors and make the data members public. The template issue is a red hering; the same rules apply as for any class: if it is an aggregate, you can use aggregate initialization; if it's not, you can't.

    -- James Kanze

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