How to compare two std::any?

Viewed 1020

There's no operator== for std::any

Am I missing something obvious or do I need to actually earn my living?

Is there some simple way to provide the operator?

https://godbolt.org/z/rdoWrcnTs

// Example program
#include <iostream>
#include <string>
#include <any>

int main()
{
    auto str1 = std::make_any<std::string> ("Hello");
    auto str2 = std::make_any<std::string> ("World");
    
    if(str1 == str2) std::cout << "same"; // error
}
1 Answers

There's no direct way to compare two objects of std::any because the underlying types may not be the same. If you know they're the same, you can write:

if(std::any_cast<std::string>(str1) == std::any_cast<std::string>(str2)) 
  // ...
Related