c++ - std::function 和由 "using"推导的函数类型不具有相同类型

标签 c++ templates template-meta-programming std-function type-deduction

下面是一个小例子来展示两种不同的函数类型的区别:

#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/

相关文章:

c++ - 我该如何实现一个奇怪的 "class"符号

c++ - 我可以在 c++0x 模板中使用 loki ObjectLevelLockable

c++ - 递归函数是否可以在不将常量作为参数发送给它的情况下了解首次调用它的函数中的常量?

c++ - 非模板类使用模板类作为成员变量

c++ - 在编译时计算一个小整数的阶乘

c++ - GetAdaptersInfo 崩溃

django - 包含的 django 模板中的错误未呈现

python - Django - 自定义 403 模板

c++ - 用于 pod 的重载运算符 ==

c++ - 使用比较器网络对固定长度数组进行非常快速的排序