是否有一种方法可以使用SFINAE来检测是否未声明非模板化的非成员函数

Is there a way to use SFINAE to detect whether a non-templated non-member function is not declared?

本文关键字:是否 未声明 检测 函数 成员 SFINAE 可以使 方法 一种      更新时间:2023-10-16

我试图用SFINAE和decltype来回答这个问题。总而言之,发布者想要一个函数,它的行为取决于是否在编译单元中声明了另一个函数(无论声明的时间是早于该函数还是晚于该函数)。

我试了如下:

auto some_function_2_impl(int) -> decltype(some_function_1(), void()) {
    cout << "Using some_function_1" << endl;
    some_function_1();
}
void some_function_2_impl(long) {
    cout << "Not using some_function_1" << endl;
}
void some_function_2() {
    return some_function_2_impl(0);
}   

但是,我得到这个错误消息:

main.cpp:4:60: error: 'some_function_1' was not declared in this scope
 auto some_function_2_impl(int) -> decltype(some_function_1(), void()) {

这就是重点,我想——我不想让some_function_2_impl的过载被定义,因为some_function_1不存在。

我想也许SFINAE需要模板工作,所以我尝试了以下(这可能有助于表明我不完全知道我在这里做什么):

template <int foo>
auto some_function_2_impl(int) -> decltype(some_function_1(), void()) {
    cout << "Using some_function_1" << endl;
    some_function_1();
}
template <int foo>
void some_function_2_impl(long) {
    cout << "Not using some_function_1" << endl;
}

但是,现在我得到以下错误:

main.cpp:5:60: error: there are no arguments to 'some_function_1' that 
depend on a template parameter, so a declaration of 'some_function_1'
must be available [-fpermissive]
 auto some_function_2_impl(int) -> decltype(some_function_1(), void()) {

我做错了什么?

函数查找立即完成,即使在模板类型中,除了当根据模板参数类型有可能进行ADL查找时。

则在类型替换后完成ADL查找。如果失败,则结果是替换失败。

由于您的函数调用不依赖于参数类型,因此这种技术将不起作用。

我们仍然可以做一些适度有趣的事情:

template<class T, class...Ts>
struct first_two_match : std::false_type{};
template<class T, class...Ts>
struct first_two_match<T,T,Ts...>:std::true_type{}; // for standard compliance: If the only Ts... that match Ts... is nothing, program ill-formed.
struct secret_type_tag {};
template<class...Ts,
  std::enable_if_t<
    (sizeof...(Ts)==0) || first_two_match<secret_tag_type,Ts...>{}
  >* =nullptr
>
secret_type_tag some_function_1(Ts&&...);
template<bool b>
using bool_t=std::integral_constant<bool, b>;
static const auto some_function_defined = bool_t<
  !std::is_same<secret_tag_type, decltype( some_function_1() )>{}
>;

现在some_function_definedstd::true_type,如果some_function_1的过载优于我的some_function_1(Ts&&...)。由于some_function_1(Ts&&...)的优先级非常低,任何"真正的"过载(也不是转发引用glomer,并且接受0个参数)都将优先考虑。

在更复杂的情况下,如果存在真正的过载,则不选择这样的低优先级过载是很棘手的。

这个仍然只是检测some_function_1是否在创建some_function_defined时被定义。骗子。