如何在编译时测试模板函数是否存在 [英] How to test if template function exists at compile time
本文介绍了如何在编译时测试模板函数是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模板函数
template<class Visitor>
void visit(Visitor v,Struct1 s)
{
}
如何用SFINAE在编译时检查这个函数是否存在
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";}
};
现场演示(只需删除 -DDEFINE_VISIT 即可查看输出开关)
Live demo (just remove -DDEFINE_VISIT to see the output switch)
这篇关于如何在编译时测试模板函数是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文