Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Willy Goat Avatar asked Jan 12 '17 02:01

Willy Goat


People also ask

What does std :: iota do C++?

std::iota in C++Assigns to every element in the range [first, last] successive values of val, as if incremented with ++val after each element is written.

How do you write iota in C++?

The one for writing Greek is ι , U+03B9, “GREEK SMALL LETTER IOTA”. The one for writing APL is ⍳ , U+2373, “APL FUNCTIONAL SYMBOL IOTA”.

What is iota algorithm?

IOTA is an open-source distributed ledger and cryptocurrency designed for the Internet of things (IoT). It uses a directed acyclic graph to store transactions on its ledger, motivated by a potentially higher scalability over blockchain based distributed ledgers.


1 Answers

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

like image 196
Jubin Chheda Avatar answered Sep 19 '22 06:09

Jubin Chheda