下面是一个小例子来展示两种不同的函数类型的区别:
#include <iostream>
#include <functional>
#include <type_traits>
template <typename T>
using BinaryOperator = T(const T&, const T&);
int main() {
std::cout << std::boolalpha
<< std::is_same<
std::function<int(const int&, const int&)>,
BinaryOperator<int>
>::value
<< std::endl;
return 0;
}
这打印出 false
这让我很困惑。这两种类型似乎是等价的。它们有何不同?
最佳答案
Both types seems to be equivalent. How are they different?
嗯……不:它们是不同的类型。
如果您查看 std::function
's page in cppreference.com , 你可以看到 std::function
是一个部分特化的类(只定义了特化)声明如下
template <class>
class function; // undefined
template <class R, class... Args>
class function<R(Args...)>;
所以你的 BynaryOperator<int>
不等于 std::function<int(const int&, const int&)>
但等同于它的模板参数。
可以看到是true
std::is_same<std::function<int(const int&, const int&)>,
std::function<BinaryOperator<int>>
>::value // ^^^^^^^^^^^^^^...................^
关于c++ - std::function 和由 "using"推导的函数类型不具有相同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54803896/