是否有一种方法可以使用SFINAE来检测是否未声明非模板化的非成员函数
Is there a way to use SFINAE to detect whether a non-templated non-member function is not declared?
我试图用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_defined
是std::true_type
,如果some_function_1
的过载优于我的some_function_1(Ts&&...)
。由于some_function_1(Ts&&...)
的优先级非常低,任何"真正的"过载(也不是转发引用glomer,并且接受0个参数)都将优先考虑。
在更复杂的情况下,如果存在真正的过载,则不选择这样的低优先级过载是很棘手的。
这个仍然只是检测some_function_1
是否在创建some_function_defined
时被定义。骗子。
相关文章:
- #ifdef和未声明的标识符
- 未声明的标识符编译暗黑破坏神 2 程序"muleview"
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- Google protobuf 时间戳未声明标识符,在 Windows 上具有C++
- 在气泡排序程序中未声明错误功能
- 我在范围内未声明的错误类有问题
- 使用未声明的标识符"sqrt"?
- 我包含了<winuser.h>,但编译器在MonitorFromWindow上抛出"未声明"
- 对类 (C++) 中的私有变量使用未声明的标识符
- 如何测试 size_t -1 是否未定义,其中 size_t 为 0?
- 我的代码中有错误,未声明的标识符
- 未定义的标识符/未声明
- 错误:在 C++ 'std'使用未声明的标识符
- 在编译器之前检测未声明的标识符
- 使用未声明的标识符'temp'
- 使用未声明的标识符"yylex"和"yyin"?
- 使用"class"关键字,后跟未声明的标识符
- 使用无效指针初始化指针声明符的行为是否未定义?
- 视觉 未声明的变量在C++中是否合法
- 是否有一种方法可以使用SFINAE来检测是否未声明非模板化的非成员函数