gpt4 book ai didi

c++ - 在成员函数尾随返回类型中使用 this 和属性?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:08:53 24 4
gpt4 key购买 nike

在此answer我给出了,在尾随返回类型中使用 this 和类 _arg 的属性作为 decltype 表达式的一部分是有意义的。可以不用,但不方便。

既不是 clang 3.0(见下文)也不是 gcc 4.5.2不过还是接受了。

#include <iostream>

class MyClass {
public:
MyClass(int i): _arg(i) {}

template <typename F>
auto apply(F& f) -> decltype(f(_arg)) {
return f(_arg);
}

template <typename F>
auto apply(F& f) -> decltype(f(*this, _arg)) {
return f(*this, _arg);
}

private:
int _arg;
};

struct Id {
template <typename V>
V operator()(V v) const { return v; }
};

struct ComplexId {
template <typename C, typename V>
V operator()(C const&, V v) { return v + 1; }
};

int main() {
Id id; ComplexId complex;

MyClass c(0);

std::cout << c.apply(id) << " " << c.apply(complex) << "\n";
}

clang 3.0 说:

$ clang++ -std=c++11 -Weverything test.cpp
test.cpp:8:38: error: use of undeclared identifier '_arg'
auto apply(F& f) -> decltype(f(_arg)) {
^
test.cpp:8:45: error: type name requires a specifier or qualifier
auto apply(F& f) -> decltype(f(_arg)) {
^
test.cpp:8:45: error: C++ requires a type specifier for all declarations
auto apply(F& f) -> decltype(f(_arg)) {
~~~~~~~~ ^
test.cpp:8:7: error: 'auto' return without trailing return type
auto apply(F& f) -> decltype(f(_arg)) {
^
test.cpp:13:39: error: invalid use of 'this' outside of a nonstatic member function
auto apply(F& f) -> decltype(f(*this, _arg)) {
^
test.cpp:13:52: error: type name requires a specifier or qualifier
auto apply(F& f) -> decltype(f(*this, _arg)) {
^
test.cpp:13:52: error: C++ requires a type specifier for all declarations
auto apply(F& f) -> decltype(f(*this, _arg)) {
~~~~~~~~ ^
test.cpp:13:7: error: 'auto' return without trailing return type
auto apply(F& f) -> decltype(f(*this, _arg)) {
^
8 errors generated.

嗯……不太好。

但是,在大多数编译器中,C++11 的支持充其量只是 hacky,我找不到标准 (n3290) 中提到的具体限制。

在评论中,Xeo 表示这可能是标准中的一个缺陷......

那么,这是否允许?

奖励:最新版本的 clang/gcc 是否支持此功能?

最佳答案

我记错了。这是a defect at some point , 但最终是 resolved and voted into the FDIS .

§5.1.1 [expr.prim.general]

If a declaration declares a member function or member function template of a class X, the expression this is a prvalue of type “pointer to cv-qualifier-seq X” between the optional cv-qualifer-seq and the end of the function-definition, member-declarator, or declarator.

因此,Clang 和 GCC 还没有正确实现它。

struct X{
// 'this' exists between the | markers
void f() const volatile | {
} |
auto g() const volatile | -> void {
} |
};

关于c++ - 在成员函数尾随返回类型中使用 this 和属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9018460/

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