Jan*_*lho 10 c++ templates type-traits c++11
如何获取一个布尔值,指示已知方法是否具有const限定符?
例如:
struct A {
void method() const {}
};
struct B {
void method() {}
};
bool testA = method_is_const<A::method>::value; // Should be true
bool testB = method_is_const<B::method>::value; // Should be false
Run Code Online (Sandbox Code Playgroud)
在type_traits标题中我发现了一个is_const我可以使用的测试,但我需要方法类型,而且我不确定如何获得它.
我尝试过:std::is_const<decltype(&A::method)>::value但它不起作用,我可以理解为什么(void (*ptr)() const) != const void (*ptr)()).
检查是否可以在const合格的左值上调用成员函数要简单得多.
template<class T>
using const_lvalue_callable_foo_t = decltype(std::declval<const T&>().foo());
template<class T>
using has_const_lvalue_callable_foo = std::experimental::is_detected<const_lvalue_callable_foo_t, T>;
Run Code Online (Sandbox Code Playgroud)
冲洗并重复,除了std::declval<const T>(),以检查是否可以在const合格的右值上调用所述函数.我认为const &&成员函数没有好的用例,所以检测这个案例是否有意义是值得怀疑的.
请参阅当前的Library Fundamentals 2 TS工作草案,了解如何实施is_detected.
检查特定指向成员函数类型的指针是否指向具有特定cv-qualifier-seq的函数类型会更复杂.这需要每个cv-qualifier-seq有 6个部分特化(const 并且const volatile是不同的cv-qualifier-seq),并且仍然无法处理重载的成员函数或成员函数模板.草绘这个想法:
template<class T>
struct is_pointer_to_const_member_function : std::false_type {};
template<class R, class T, class... Args>
struct is_pointer_to_const_member_function<R (T::*)(Args...) const> : std::true_type {};
template<class R, class T, class... Args>
struct is_pointer_to_const_member_function<R (T::*)(Args...) const &> : std::true_type {};
template<class R, class T, class... Args>
struct is_pointer_to_const_member_function<R (T::*)(Args...) const &&> : std::true_type {};
template<class R, class T, class... Args>
struct is_pointer_to_const_member_function<R (T::*)(Args..., ...) const> : std::true_type {};
template<class R, class T, class... Args>
struct is_pointer_to_const_member_function<R (T::*)(Args..., ...) const &> : std::true_type {};
template<class R, class T, class... Args>
struct is_pointer_to_const_member_function<R (T::*)(Args..., ...) const &&> : std::true_type {};
Run Code Online (Sandbox Code Playgroud)
如果你想const volatile成为,true那么沿着这些方向划出另外6个部分专业.
原因std::is_const<decltype(&A::method)>::value不起作用的是const成员函数不是const(成员函数).const对于const intvs来说,这不是一个顶级的方式int.
我们可以做的是使用的类型特征void_t测试我们是否可以调用methodconst T:
template <typename... >
using void_t = void;
template <typename T, typename = void>
struct is_const_callable_method : std::false_type { };
template <typename T>
struct is_const_callable_method<T, void_t<
decltype(std::declval<const T&>().method())
> > : std::true_type { };
Run Code Online (Sandbox Code Playgroud)