c – 为什么声明`void(* pf)(int)= bar;`在下面的代码片段中触发
发布时间:2020-12-16 09:53:14 所属栏目:百科 来源:网络整理
导读:这是 my prior question的延续.注意声明void(* pf)(int)= bar;触发static_assert.我不明白为什么.另请注意,如果我替换barby bar const int在此声明中,代码编译. #include iostream#include type_traitstemplatetypename Tvoid bar(T t){ static_assert(std::
这是
my prior question的延续.注意声明void(* pf)(int)= bar;触发static_assert.我不明白为什么.另请注意,如果我替换barby bar< const int>在此声明中,代码编译.
#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失败.
void(*pf)(int) = bar; // [T = int]
那是因为你现在已经明确指定T是const int,并且它不再被推断为int. void(*pf)(int) = bar<const int>; // [T = const int] 您仍然可以为函数void(const int)创建void(*)(int)类型的函数指针,因为顶级consts不是函数签名的一部分. 将const添加到函数指针类型没有帮助,因为相同的原因,函数参数类型中的顶级const在推断T之前被丢弃,并且它导致与第一个示例相同的行为. void(*pf)(const int) = bar; // [T = int] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |