Thread: Can I sum a std::vector at compile time?

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    144

    Can I sum a std::vector at compile time?

    Hi everyone. I have adapted this from page 9 of "A Tour of C++". I can't seem to sum the values in a std::vector<double> at compile time. Is it possible?
    Code:
    #include <iostream>
    #include <vector>
    
    using std::vector;
    
    constexpr double sum(const vector<double>& v)
    {
        double s = 0.0;
    
    /* Will not compile:
    
        for (auto& x : v)
            s += x;
    
    */
    
    /* Will not compile:
    
        for (vector<double>::size_type i = 0; i < v.size(); ++i)
            s += v[i];
    
    */
        return s;
    }
    
    int main()
    {
        vector<double> v {1.2, 3.4, 4.5};
    
        const double s1 = sum(v);
    
        std::cout << s1 << std::endl;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    What exactly is the point of the exercise?

    Do you realize that you can't modify a const, and that a constexpr is a compile time constant expression (every thing must be computable at compile time.

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think the only real wrinkle in something like this is that I'm not sure vectors can be initialized at compile time.

    It is definitely possible to achieve something similar. Here's a template meta-programming version.

    Code:
    C:\Users\jk\Desktop>more sum.cpp
    #include <iostream>
    #include <cstddef>
    
    static constexpr double arr[3] = {1.2, 3.4, 4.5};
    
    template <typename T, const T *arr, const size_t idx> struct sum
    {
        static constexpr T value = arr[idx-1] + sum<T,arr,idx-1>::value;
    };
    
    template<typename T, const T *arr> struct sum<T, arr, 1>
    {
        static constexpr T value = arr[0];
    };
    
    
    int main()
    {
        std::cout << sum<double, arr, 3>::value << std::endl;
    }
    
    C:\Users\jk\Desktop>g++ -std=c++11 -c sum.cpp
    
    C:\Users\jk\Desktop>g++ sum.o -o sum
    
    C:\Users\jk\Desktop>sum
    9.1

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 04-05-2015, 11:42 AM
  2. Replies: 2
    Last Post: 01-12-2013, 10:11 AM
  3. Getting compile time.
    By ThatDudeMan in forum C Programming
    Replies: 2
    Last Post: 10-13-2010, 12:15 PM
  4. Compile-Time Help
    By brayden37 in forum C++ Programming
    Replies: 0
    Last Post: 10-11-2001, 03:10 PM

Tags for this Thread