简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM