简体   繁体   中英

Why isn't std::iota constexpr?

The following program prints out a shuffled deck of cards (as integers):

#include <array>
#include <algorithm>
#include <random>
#include <iostream>

typedef unsigned int card;
typedef std::array<card, 52> deck;
auto shuffled_deck(){
    deck d = {};
    std::iota(d.begin(), d.end(), 0);
    std::shuffle(d.begin(), d.end(), std::default_random_engine());
    return d;
}

int main(){
    for(auto& i: shuffled_deck()) std::cout << i << ", ";
}

Compiled with g++ -std=c++17 the program runs and prints:

18, 34, 27, 46, 11, 3, 12, 19, 33, 21, 41, 13, 36, 49, 40, 22, 8, 9, 28, 2, 6, 30, 50, 24, 37, 32, 35, 4, 15, 45, 47, 43, 14, 44, 20, 23, 29, 7, 31, 51, 26, 10, 42, 48, 0, 38, 5, 16, 17, 1, 25, 39,

This is great, but intuition tells me that this deck could be created at compile-time, so I make the shuffled_deck method constexpr

constexpr auto shuffled_deck(){
    deck d = {};
    std::iota(d.begin(), d.end(), 0); // Error! Iota isn't constexpr!
    std::shuffle(d.begin(), d.end(), std::default_random_engine());
    return d;
}

Compiling with g++ -std=c++17 gives you compilation error saying that std::iota is not constexpr . My question is why? Surely std::iota is determinable at compile-time. Is the standard library just lagging behind on this feature?

This should be proposed to be added to the standard. As it stands now it just isn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM