How to test if template function exists at compile time

浪子不回头ぞ 提交于 2019-12-11 10:59:22

问题


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


回答1:


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)



来源:https://stackoverflow.com/questions/31605368/how-to-test-if-template-function-exists-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!