首页 > 解决方案 > 如何为非类型模板参数类型考虑 ADL

问题描述

我想在函数调用中查找期间考虑非类型模板参数的命名空间中的函数。

例如:

template<auto& N>
struct test_nontype {
    int call() {
        return f(*this);  // error: 'f' was not declared in this scope
    }
};

template<typename T>
struct test_type {
    int call() {
        return f(*this);  // ok, f is found in ns via ADL
    }
};


namespace ns {
    static struct type_in_ns {} value;
    int f(test_nontype<value>) {
        return 3;
    }
    int f(test_type<type_in_ns&>) {
        return -3;
    }
}

int main() {
    int x = test_type<ns::type_in_ns&>{}.call();
    return x + test_nontype<ns::value>{}.call();
}

使用类型它工作正常,但最后一行无法编译,因为int ns::f(test_nontype<ns::value>)找不到。

template<auto& N, typename = decltype(N)> struct test_nontype {如果有替代品,我宁愿不添加参数,因为添加模板参数只会使界面更加混乱(我必须添加注释来解释它是用于 ADL,但 IDE 仍然建议添加类型名称,并且它还会增加更多的噪音来编译错误)

还有哪些其他解决方法?

标签: c++argument-dependent-lookup

解决方案


推荐阅读