C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发`static_assert`?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是 my prior question的延续.注意声明void(* pf)(int)= bar;触发static_assert.我不明白为什么.另请注意,如果我替换barby bar< const int>在此声明中,代码编译.

@H_616_7@#include <iostream> #include <type_Traits> template<typename T> void bar(T t) { static_assert(std::is_same<T,const int>::value,"Error!"); std::cout << t << '\n'; } int main() { // static_assert doesn't fire because T==const int bar<const int>(1); // But here static_assert fires because T==int (see the error messagE). Why is this? // If I replace `bar` by `bar<const int>` below the code compiles. void(*pf)(int) = bar; pf(1000); }

Live example

解决方法

这种行为非常简单. T从下面的函数指针类型推导为int,因此static_assert失败.

@H_616_7@void(*pf)(int) = bar; // [T = int]

是因为你现在已经明确指定T是const int,并且它不再被推断为int.

@H_616_7@void(*pf)(int) = bar<const int>; // [T = const int]

您仍然可以为函数void(const int)创建void(*)(int)类型的函数指针,因为顶级consts不是函数签名的一部分.

将const添加函数指针类型没有帮助,因为相同的原因,函数参数类型中的顶级const在推断T之前被丢弃,并且它导致与第@L_197_11@示例相同的行为.

@H_616_7@void(*pf)(const int) = bar; // [T = int]

大佬总结

以上是大佬教程为你收集整理的c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发`static_assert`?全部内容,希望文章能够帮你解决c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发`static_assert`?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。