我找到了有趣的东西.错误消息说明了一切.在获取非静态成员函数的地址时不允许使用括号的原因是什么?我在gcc 4.3.4上编译了它.
#include <iostream>
class myfoo{
public:
int foo(int number){
return (number*10);
}
};
int main (int argc, char * const argv[]) {
int (myfoo::*fPtr)(int) = NULL;
fPtr = &(myfoo::foo); // main.cpp:14
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:main.cpp:14:错误:ISO C++禁止获取非限定或带括号的非静态成员函数的地址,以形成指向成员函数的指针.说'&myfoo :: foo'
考虑以下代码:
int x = 0;
template<int& I>
struct SR {};
template<int* I>
struct SP {};
SR<(x)> sr;
SP<&(x)> sp;
int main(void)
{
}
Run Code Online (Sandbox Code Playgroud)
clang ++ 3.8.0抱怨:
main.cpp:10:5: error: non-type template argument does not refer to any declaration
SP<&(x)> sp;
^~~
main.cpp:6:15: note: template parameter is declared here
template<int* I>
^
Run Code Online (Sandbox Code Playgroud)
g ++ 6.1.0抱怨:
main.cpp:10:8: error: template argument 1 is invalid
SP<&(x)> sp;
^
Run Code Online (Sandbox Code Playgroud)
当然,如果我删除括号,一切正常,如SP<&x> sp;.但是我在C++ 14标准中找不到任何会在这里产生影响的东西.此外,为什么参考案例没问题,但指针案例不好?编译器是否正确拒绝该程序?
以下代码在使用 -std=c++11 的 GCC 6.3 中可以正常编译。
template <typename T>
struct MetaFunction
{
static int value;
};
#define MY_MACRO(T) (MetaFunction<T>::value)
template <class T, const int* p = &MY_MACRO(T)>
struct Foo
{
void DoSomething()
{
}
};
int main()
{
Foo< int > f;
f.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
但如果指定 -std=c++14 则会发出以下错误:
main.cpp:19:14: error: '& MetaFunction<int>::value' is not a valid template argument for 'const int*' because it is not the address of a variable
Foo< int > f;
^
Run Code Online (Sandbox Code Playgroud)
无论指定 -std=c++11 还是 -std=c++14,Clang 3.8 都会给出类似的错误。 …