#include <type_traits>
// Base template
template<class T>
struct is_const_member_func_ptr;
// Specialize for pointers to non-const member function
template<class T, class C, class ... A>
struct is_const_member_func_ptr<T (C::*)(A...)> : std::false_type {};
// Specialize for pointers to const member function
template<class T, class C, class ... A>
struct is_const_member_func_ptr<T (C::*)(A...) const> : std::true_type {};
// Convenient constant template
template<class T>
inline constexpr bool is_const_member_func_ptr_v = is_const_member_func_ptr<T>::value;
用法:
class D {};
static_assert(is_const_member_func_ptr_v<void (D::*)() const> == true);
static_assert(is_const_member_func_ptr_v<void (D::*)()> == false);
2条答案
按热度按时间jjjwad0x1#
我不认为有一个标准的特征来检查这种类型的稳定性,但它是一个相对直接的写:
用法:
示例:https://godbolt.org/z/Y9EjY5jzf
编辑:使用实际定义的成员函数的示例
实时:https://godbolt.org/z/9fvYs834W
f1tvaqid2#
在C++中,函数不是一等公民:不能有函数类型的对象(可以有函数对象,但这是不同的概念)。
void (D::*)() const
是一个指针类型。std::is_const
将告诉您指针是否为常量,因此:std::is_const_v<void (D::*)() const> == false
;std::is_const_v<void (D::* const)()> == true
.没有标准的特征来检查一个成员函数是否有const限定符。然而,你可以自己做。François Andrieux的答案是做这个的传统方法,但是正如在评论中提到的,你需要48个专门化来完成它。
下面是另一种也许更简洁的方式:
Demo