bodzcount
bodzcount

Reputation: 105

Enabling a member function only if template parameter has member function

I have seen similiar questions, that already contain solutions, for example this one: Is it possible to write a C++ template to check for a function's existence?

However I am wondering why my solution is working on VC2015 but not on GCC5.1. GCC gives me the following error:

error: ‘get_result’ is not a member of ‘std::remove_reference_t>> > {aka main()::}’ templatedecltype(&std::remove_reference_t::get_result)(TSink)>

my code:

template <typename TSink>
struct Consume{
    ...
    TSink& _sink;
    Consumer(TSink& sink) : _sink(sink){};
    ...
    template<typename = decltype(&std::remove_reference_t<TSink>::get_result)(TSink)>
    auto
    get_result()
    {
        return _sink.get_result();
    }
}

Upvotes: 0

Views: 82

Answers (1)

TartanLlama
TartanLlama

Reputation: 65580

SFINAE should only work on template parameters in the immediate context of a template.

You can bring TSink into this immediate context by simply adding another template parameter with a default argument:

template<typename Sink = TSink,
         typename = decltype(&std::remove_reference_t<Sink>::get_result)(Sink)>
auto
get_result()
{
    return _sink.get_result();
}

Upvotes: 2

Related Questions