大佬教程收集整理的这篇文章主要介绍了c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发`static_assert`?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@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); }
@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@示例相同的行为.
以上是大佬教程为你收集整理的c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发`static_assert`?全部内容,希望文章能够帮你解决c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发`static_assert`?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。