can we use vectors in compile time programming?

Hi,

We can program with complex numbers during compile time like this:

1
2
3
constexpr complex conc{ 7.88 };
constexpr complex s{ 5.91 };
constexpr auto t = conc + s;


this is because complex has a constexpr constructor.
Now what if we want to work with vectors at compile time? after all vector constructors are also marked with constexpr?


 
constexpr  vector v{ 1,4,8,12,34,66 };



this does not compile because we have heap allocation! but then why are vector constructors marked constexpr??



Thanks for any help...




Just because a certain standard mandates something doesn't mean a compiler has actually implemented it yet.

Modules and std::format are two C++20 features still pending with every compiler that isn't MSVC++.
> Do compilers support that feature?

Current versions of the mainstream compilers (libraries) do. For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <numeric>

constexpr long long foo( std::size_t n, int v )
{
    const std::vector<int> vec( n, v ) ;
    return std::accumulate( vec.begin(), vec.end(), 0LL ) ;
}

int main()
{
    constexpr long long s = foo( 27, 154 ) ; 
    static_assert( s == 27*154 ) ;
}

http://coliru.stacked-crooked.com/a/39e716f46cebd9c5
You can use std::vector in constexpr contexts but there is, as far as I know, no way to construct a std::vector at compile time and make it survive until runtime.

The following is still an error:

 
constexpr std::vector<int> vec{1, 2, 3}; // error 
Last edited on
Since C++20, dynamic memory can now be used totally within a constexpr function. See https://www.cppstories.com/2021/constexpr-new-cpp20/

Containers that use dynamic memory (such as std::vector) have been 'changed' so that they also support dynamic memory within a compile constexpr context. See https://www.cppstories.com/2021/constexpr-vecstr-cpp20/

But the big limitation is that whilst these are evaluated at compile time, their 'lifetime' ends with the end of compilation. You can't (at present) initialise dynamic memory at compile-time and have it available initialised at run-time. You can with std::array as that doesn't use dynamic memory (its just a wrapper around c-style arrays).
> no way to construct a std::vector at compile time and make it survive until runtime.

The standard does not allow it; it requires that allocation and deallocation must be 'within the evaluation of the constant expression'
https://eel.is/c++draft/expr.const#5.18

This is fine:
1
2
// fine: allocation and deallocation are within the evaluation of the constant expression
constexpr std::size_t n = std::vector<int> { 0, 1, 2, 3, 4, 5, 6 }.size() ;



Last edited on
Topic archived. No new replies allowed.