如何解决无法从decltype中获取指向成员函数的指针
我发现我无法使用类实例&decltype(c)::f
来f
来获取指向成员函数c
的指针,但是我可以&C::f
来获取该指针成员函数,使用类类型C
,我相信它与decltype(c)
相同。
请参见以下最小示例:
struct C{
int f()
{
return 5;
}
} c;
template<typename T,T t,typename S,S*s> void callCf()
{
(s->*t)();
}
int main()
{
callCf<decltype(&decltype(c)::f),&decltype(c)::f,C,&c>();
}
编译后得到:
In function 'int main()':
15:3: error: parse error in template argument list
15:58: error: no matching function for call to 'callCf()'
15:58: note: candidate is:
8:49: note: template<class T,class S,S* s> void callCf()
8:49: note: template argument deduction/substitution failed:
15:58: error: template argument 2 is invalid
按预期使用以下作品:
int main()
{
callCf<decltype(&decltype(c)::f),&C::f,&c>();
}
即使这样有效:
int main()
{
using tC = decltype(c);
callCf<decltype(&decltype(c)::f),&tC::f,&c>();
}
这也有效:
template<typename T>
struct forward_type{
typedef T type;
};
int main()
{
callCf<decltype(&decltype(c)::f),&forward_type<decltype(c)>::type::f,&c>();
}
我的问题是:为什么不能使用decltype来获取指向像这样的&decltype(c)::f
成员函数的指针?
编辑:@Paul Sanders在评论中显示最小示例在c++17
中有效。我仍在使用c++14
。 c++17
是否包括对语言的一些更改,这些更改使我的最小示例得以编译?
解决方法
c
是一个左值,所以decltype(c)
不会返回C
类型本身,这就是decltype(c)::f
不起作用的原因。 decltype(c)
实际上将返回C&
引用类型:
- 如果参数是类型为
T
的任何其他表达式,并且
...
b)如果expression
的值类别是 lvalue ,则decltype会产生T&
;
...
您可以使用std::remove_reference/_t
从C
获取C&
类型,例如:
int main()
{
callCf<
decltype(&std::remove_reference_t<decltype(c)>::f),&std::remove_reference_t<decltype(c)>::f,std::remove_reference_t<decltype(c)>,&c
>();
}
然后可以使用using
语句来简化以下内容:
int main()
{
using tC = std::remove_reference_t<decltype(c)>;
callCf<decltype(&tC::f),&tC::f,tC,&c>();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。