我有这样的课:
class Test { public: bool bar(int &i,char c) // some arguments are passed by ref,some are by value {/*...*/} bool foo(/*...*/) {} };
而且我不想重复调用bar1 / bar2等,然后一次又一次地检查返回值,所以我写了一个宏和可变参数模板来处理这些事情
#define help_macro(object,memfn,...) help_func(#object "." #memfn,\ object,&decltype(object)::memfn,##__VA_ARGS__) template<class T,typename Func,typename... Args> void help_func(char const * name,T &&object,Func memfn,Args&&... args) { auto ret = (object.*memfn)(forward<Args>(args)...); cout<<name<<":\t" <<(ret ? "OK" : "Oops") // maybe I'll throw an exception here <<endl; }
并像这样使用它
int i = 0; Test t; help_macro(t,bar,i,'a');
它适用于g -4.7 / Debian,但ICC13.0 / Win拒绝编译它(一个非常奇怪的错误信息)
main.cpp(37): error : type name is not allowed
help_macro(t,‘a’);
^
main.cpp(37): error : expected a “)”
help_macro(t,‘a’);
^
解决方法
编辑:实际上已经费心去测试我的理论,结果证明我错了,在那种情况下,decltype(t)是Test,可以通过static_assert(std :: is_same< decltype(t),Test> :: value,“不是参考“)
所以ICC(或它使用的EDG前端)可能只是不能正确支持在嵌套名称说明符中使用decltype,这已被DR 743更改
使用std :: decay会让ICC接受它,因此是一个有用的解决方法.
原创,错误,答案:
我认为ICC就在这里,decltype(对象)实际上是Test&并且引用类型不能包含成员,因此& decltype(t):: memfn格式不正确.
代码可以简化为:
struct Test { void foo() {} }; int main() { Test t; auto p = &decltype(t)::foo; }
哪个G和Clang接受,但ICC拒绝,正确恕我直言.
您可以使用std :: remove_reference或std :: decay来修复它
#include <type_traits> // ... Test t; auto p = &std::decay<decltype(t)>::type::foo;