Can we use the detection idiom to check if a class has a member function with a specific signature?

蓝咒 提交于 2019-12-04 12:43:30

Without changing your type_traits, you may do

template<typename T, T> struct helper {};

template<class T>
using bar_t = decltype(helper<const int& (T::*)(int&&), &T::bar>{});

Demo

0xbadf00d

Adapting the ideas of dyp and Jarod42, I've came up with

template<class T, typename... Arguments>
using bar_t = std::conditional_t<
    true,
    decltype(std::declval<T>().bar(std::declval<Arguments>()...)),
    std::integral_constant<
        decltype(std::declval<T>().bar(std::declval<Arguments>()...)) (T::*)(Arguments...),
        &T::bar
    >
>;

Notice that bar_t will be the return type of a bar call. In this way, we stay consistent with the toolkit. We can detect the existence by

static_assert(type_traits::is_detected_v<bar_t, foo, int&&>, "not detected");

However, while this solution does exactly what I intended, I hate that I need to write "so much complicated code" for every method I want to detect. I've asked a new question targeting this issue.

I don't think this works for checking const qualifiers.

decltype(std::declval<T>().bar(std::declval<Arguments>()...)) (T::*)(Arguments...)

always produces a non-const function pointer type, whereas &T::bar will produce a const function pointer if bar is marked const.

This will then fail trying to convert the const pointer type to the non-const pointer type for storage in integral_constant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!