如何比较两个 std::any?

0xb*_*00d 7 c++ c++17

std::any 没有运算符 ==

我是否错过了一些明显的事情,或者我是否需要真正谋生?

有没有一些简单的方法来提供操作员?

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
}
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 3

没有直接的方法来比较两个对象,std::any因为底层类型可能不同。如果你知道它们是相同的,你可以写:

if(std::any_cast<std::string>(str1) == std::any_cast<std::string>(str2)) 
  // ...
Run Code Online (Sandbox Code Playgroud)