【发布时间】:2015-09-17 13:43:56
【问题描述】:
我正在尝试使用 SFINAE 和 decltype 回答 this question。总而言之,发布者想要一个根据编译单元中是否声明另一个函数(无论是早于还是晚于相关函数声明)而行为不同的函数。
我尝试了以下方法:
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()) {
我做错了什么?
【问题讨论】:
-
SFINAE 是替换失败不是错误:如果您的代码中没有前两个术语,则无法利用它。
-
@black:有没有办法将调用不存在的非模板化函数变成替换失败?
-
你可以使用预处理器符号来区分
-
“定义”还是“声明”?它们的意思完全不同。
-
@T.C.:说得好,我的意思是声明
标签: c++ templates c++11 sfinae decltype