2

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

user152508
  • 3,053
  • 8
  • 38
  • 58
  • [Related](http://stackoverflow.com/questions/18936259/sfinae-detect-existence-of-a-template-function-that-requires-explicit-specializ) (but no answer accepted yet), [may be useful](https://blog.quasardb.net/sfinae-hell-detecting-template-methods/) (although a bit depressing). – Quentin Jul 24 '15 at 08:17

1 Answers1

3

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)

TartanLlama
  • 63,752
  • 13
  • 157
  • 193