user152508
user152508

Reputation: 3141

How to test if template function exists at compile time

I have the following template function

template<class Visitor>
void visit(Visitor v,Struct1 s)
{
}

How to check if this function exists at compile time with SFINAE

Upvotes: 2

Views: 710

Answers (1)

TartanLlama
TartanLlama

Reputation: 65770

Without more details I can only guess what you have available, but here's a possible solution:

//the type of the call expression to visit with a given Visitor
//can be used in an SFINAE context
template <class Visitor>
using visit_t = decltype(visit(std::declval<Visitor>(), std::declval<Struct1>()));

//using the void_t pattern
template <typename Visitor, typename=void>
struct foo
{
    void operator()(){std::cout << "does not exist";}   
};

template <typename Visitor>
struct foo<Visitor,void_t<visit_t<Visitor>>>
{
    void operator()(){std::cout << "does exist";}   
};

Live demo (just remove -DDEFINE_VISIT to see the output switch)

Upvotes: 3

Related Questions