Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Since C++17 std::any is introduced. One can now write code like this

#include <iostream>
#include <any>
#include <string>

int main () {
    const double d = 1.2;
    std::any var = d;
    const std::string str = "Hello World";
    var = str;
}

A double is assigned to the variable var and than a std::string was assigned to it.

Why has std::any been introduced?

I think this is violating the least astonishment rule, because I find it hard to think of a situation, where this can be used to express more clearly, what I like to express.

Can somebody give me a good example, when std::any is beneficial.

https://gcc.godbolt.org/z/-kepOD

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
252 views
Welcome To Ask or Share your Answers For Others

1 Answer

When to Use
void* as an extremely unsafe pattern with some limited use cases, std::any adds type-safety, and that’s why it has some real use cases.

Some possibilities:

  • In Libraries - when a library type has to hold or pass anything without knowing the set of available types.
  • Parsing files - if you really cannot specify what are the supported types.
  • Message passing.
  • Bindings with a scripting language.
  • Implementing an interpreter for a scripting language
  • User Interface - controls might hold anything
  • Entities in an editor
    (ref)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...