gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:50:42 26 4
gpt4 key购买 nike

我有以下模板函数

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

Live demo (只需删除 -DDEFINE_VISIT 即可查看输出开关)

关于c++ - 如何在编译时测试模板函数是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31605368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com