Quick Q: How to require an exact function signature in the detection idiom?

Save to:
Instapaper Pocket Readability

Quick A: Use is_detected

Recently on SO:

How to require an exact function signature in the detection idiom?

With C++17 is_detected, you may do

template <typename T, typename Ret, typename Index>
using subscript_t = std::integral_constant<Ret (T::*) (Index), & T::operator[]>;

template <typename T, typename Ret, typename Index>
using has_subscript = is_detected<subscript_t, T, Ret, Index>;

static_assert(has_subscript<std::vector<int>, int&, std::size_t>::value, "!");
static_assert(!has_subscript<std::vector<int>, int&, int>::value, "!");

Add a Comment

You must sign in or register to add a comment.

Comments (1)

1 0

mechacrash said on Jul 26, 2017 03:28 PM:

I currently do something similar (untested - I use a slightly different implementation of the detection idiom, see the link below):


template <class T, class Sig>
using has_func = decltype(std::mem_fn<Sig>(&T::func));

static_assert(is_detected_v<has_func, foo, void(int) const>);


Though I have a question about this and private/protected member access currently unanswered here: https://www.reddit.com/r/cpp_questions/comments/6pg44a/whos_right_gccmsvc_or_clang_and_why/

given that 'struct detector' is exposition only, I think there needs to be some clarification on this - as it may limit its usefulness!