0

我认为 C++ 如何处理函数指针和 std::function 是一个很大的限制,目前不可能以优雅的方式比较两个不同类型的任意函数。

我现在想知道 C++17 是否会通过引入std::any

void foo(int a) {}
int bar(float b) {}

void main()
{
    std::any oneFoo = std::make_any(foo);
    std::any oneBar = std::make_any(bar);
    std::any anotherFoo = std::make_any(foo);

    bool shouldBeFalse = (oneBar == oneFoo);
    bool shouldBeTrue = (oneFoo == anotherFoo);
}

这会像我预期的那样表现吗?

4

1 回答 1

1

比较函数指针很容易。您甚至不需要使用C++17,但它有助于缩短代码:

#include <iostream>

void foo(int a) {}
int bar(float b) { return 0; }

template <class A, class B> bool pointer_equals(A *a, B *b) {
  if
    constexpr(std::is_same<A, B>::value) { return a == b; }
  else {
    return false;
  }
}

int main(int, char *[]) {
  std::cout << "Should be false: " << pointer_equals(foo, bar) << "\n"
            << "Should be true: " << pointer_equals(foo, foo) << "\n";
  return 0;
}

问题是:函数只是一种可调用对象,其中有很多不同的可能调用对象C++。从功能的角度来看,指针相等有点弱。

于 2017-04-13T12:08:33.153 回答