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

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c++ - When should I use std::any

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

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

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...