我从探索 C++ 的不寻常角落中得到真正的乐趣。从 this question 了解了真正的函数类型而不是函数指针,我试着搞乱函数类型并想出了这个奇怪的案例:
typedef int Func(int);
int Foo(int x) { return 1; }
int main()
{
const Func*& f = &Foo;
return 0;
}
因为 &Foo
是 Func*
类型的右值,我想我应该可以把它放在一个 const 引用中,但是我从 g++ 4.6 得到这个错误:
funcTypes.cpp: In function ‘int main()’:
funcTypes.cpp:7:23: error: invalid initialization of non-const reference of type ‘int (*&)(int)’ from an rvalue of type ‘int (*)(int)’
但是 f
是 const!对我来说很明显, const 对函数的应用(或对指针的引用/引用等)被简单地忽略了;这段代码编译得很好:
template <typename A, typename B>
struct SameType;
template <typename A>
struct SameType<A, A> { };
typedef int Func(int);
int main()
{
SameType<const Func, Func>();
return 0;
}
我猜这就是 boost 实现其 is_function
的方式类型特征,但我的问题是 - 为什么 C++ 通过忽略它而不是禁止它来允许它?
编辑:我现在意识到在第一个示例中 f
是非常量并且 const FuncPtr& f = &Foo
确实有效。然而,这只是背景,真正的问题是上面那个。
最佳答案
But f is const!
不,不是。你搞糊涂了
const Func*& f = &Foo;
与
Func* const& f = &Foo;
前者是对常量指针的非常量引用。后者是对非常量指针的常量引用。
这就是为什么我总是在 */& 之前而不是在类型之前写常量。我总是把第一个案例写成
Func const*& f = &Foo;
然后从右到左阅读:对指向 const Func 的指针的引用。
关于c++ - 为什么 C++ 允许但忽略将 const 应用于函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8412691/