gpt4 book ai didi

c++ - 为什么编译器提示使用未声明的标识符 'f1'

转载 作者:行者123 更新时间:2023-11-30 01:46:43 26 4
gpt4 key购买 nike

int f() {
return 1;
}

int g(int i) {
return i;
}
template <typename F1, typename F2>
class Composer {
public:
Composer(F1 *ff1, F2 *ff2): f1(ff1), f2(ff2) {}
/*
auto operator() () const ->
// if i insert this code,
// here compiler complains "use undeclared identifier 'f1'"
decltype(f2(f1())) {
return f2(f1());
}
*/
template<typename... Ps>
auto operator() (Ps... ps) const -> decltype(f2(f1(ps...))) {
return f2(f1(ps...));
}
private:
F1 *f1;
F2 *f2;
};
int main() {
Composer<decltype(f), decltype(g)> c(f, g);
// compiler complains here "no matching function for call to
// object of type Composer<decltype(f), decltype(g)>"
c();
}

我想知道上面的代码有什么问题。为什么编译器提示调用 c() 没有匹配函数?如果我插入非模板函数“operator() () const”,为什么编译器会提示 f1 未声明?感谢阅读,我很想知道答案,请帮助我!

最佳答案

[basic.scope.class]/p1:

1) The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, default arguments, exception-specifications, and brace-or-equal-initializers of non-static data members in that class (including such things in nested classes).

trailing-return-type 不在列表中。因此,适用一般规则 - f1f2 必须在使用前声明。

在 C++14 中,您可以返回 decltype(auto) 并删除结尾的返回类型。否则,您可以将它们向上移动或使用 declval

关于c++ - 为什么编译器提示使用未声明的标识符 'f1',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707990/

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