簡體   English   中英

如何從類中獲取成員函數的返回類型?

[英]How to get the return type of a member function from within a class?

以下程序產生了與clang的編譯錯誤,盡管它傳遞給其他編譯器:

#include <utility>

struct foo
{
  auto bar() -> decltype(0)
  {
    return 0;
  }

  using bar_type = decltype(std::declval<foo>().bar());
};

int main()
{
  return 0;
}

clang產量:

$ clang -std=c++11 clang_repro.cpp 
clang_repro.cpp:10:48: error: member access into incomplete type 'foo'
  using bar_type = decltype(std::declval<foo>().bar());
                                               ^
clang_repro.cpp:3:8: note: definition of 'foo' is not complete until the closing '}'
struct foo
       ^
1 error generated.

這個程序是非法的,如果是這樣,有沒有正確的方法來定義foo::bar_type

clang細節:

$ clang --version
Ubuntu clang version 3.5-1ubuntu1 (trunk) (based on LLVM 3.5)
Target: x86_64-pc-linux-gnu
Thread model: posix

g ++ 4.9發出相同的錯誤

我不確定這是否是無效代碼,因為declval允許不完整的類型,並且不評估decltype表達式。
rightføld在他的回答中解釋了為什么這段代碼無效。

你可以使用std :: result_of

using bar_type = std::result_of<decltype(&foo::bar)(foo)>::type;

這實際上是這樣實現的:

using bar_type = decltype((std::declval<foo>().*std::declval<decltype(&foo::bar)>())());

這與問題中的代碼之間的區別在於使用指向成員的操作符( .* )而不是成員訪問操作符( . ),並且它不需要完成類型,這由此證明碼:

#include <utility>
struct foo;
int main() {
    int (foo::*pbar)();
    using bar_type = decltype((std::declval<foo>().*pbar)());
}

§7.1.6.2說:

對於表達式e ,由decltype(e)表示的類型定義如下:

  • 如果e是未表示的id-expression或未加密的類成員訪問(5.2.5),則decltype(e)e命名的實體的類型。 ...
  • ...

§5.2.5說:

對於第一個選項(點),第一個表達式應具有完整的類類型。 ...

§9.2說:

一類被認為是在閉合完全定義的對象類型(3.9)(或完全型) }的類指定符。 ...

decltype(std::declval<foo>().bar()) (以及std::declval<foo>().bar() )出現在結束}之前,所以foo不完整,所以std::declval<foo>().bar()格式不正確,所以clang是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM