Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error : expected primary-expression before 'decltype'

Tags:

c++

windows

mingw

I am trying to find the type of variable. In stackoverflow it is mentioned that decltype() is used for that purpose. But when I tried to used it is throwing me the error as I mentioned in title.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int x = 4;
    cout << decltype(x);
    return 0;
}

I expected int but it showing as error. error: expected primary-expression before 'decltype'

like image 386
Samer Avatar asked Jun 27 '26 16:06

Samer


1 Answers

Types aren't first class objects. You can't pass a type to a function, and cout << decltype(x) is exactly that, passing a type to a function (though beautified by the operator).

To get an info about the type of a variable, you can

  1. Read the code. If the type of an object is int, don't bother printing it.
  2. Step through your program with a debugger. It shows the type of variables.
  3. Use this (non-standard) function template

    template <class T> void printType(const T&)
    {
        std::cout << __PRETTY_FUNCTION__ << "\n";
    }
    
    printType(x);
    
  4. Use Boost.

    #include <boost/type_index.hpp>
    
    std::cout << boost::typeindex::type_id_with_cvr<decltype(x)>().pretty_name() << "\n";
    
like image 172
lubgr Avatar answered Jun 30 '26 09:06

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!