如何在编译时测试模板函数是否存在

How to test if template function exists at compile time

本文关键字:函数 是否 存在 测试 编译      更新时间:2023-10-16

我有以下模板函数

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

如何在编译时使用SFINAE检查此函数是否存在

没有更多的细节,我只能猜测你有什么可用的,但这里有一个可能的解决方案:

//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";}   
};

实时演示(只需删除-DDEFINE_VISIT以查看输出开关)