【C++】問題解決: error: expected primary-expression before ‘decltype’ (內含正確使用方式範例)

紀錄 `decltype` 「expected primary-expression」錯誤 — 這是型態運算子,不能直接當成值輸出。

前言

此為 C++11 decltype 上遇到以下問題,個人的解決問題筆記

error: expected primary-expression before decltype

解決方法

這是個邏輯問題,
我們可以直接思考一個問題:

cout << int;

這樣的程式碼正確嗎?

如果你想通了,那你應該就知道不能這樣做。
(資料型態是不能這樣印出來的!!!)

正確使用方式範例

int x = 0;
decltype(x) y = 1;           // y -> int 

這裡y的類別就是 int ,是經由 decltype(x) 得到的。

你應該是想要這樣做

雖然還不夠完美,但至少是能得到類別名稱的方法。

cout << typeid(x).name();

reference

Licensed under CC BY-NC-SA 4.0
使用 Hugo 建立
主題 StackJimmy 設計