Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::remove_reference not removing the reference

This prints the cout, which means the type of T is int&

    #include <vector>
    #include <sys/types.h>
    using namespace std;
    using var_t = std::variant<int, long, double, std::string>;

    int main(int argc, char* argv[]) {
     std::vector<var_t> vec = {10};
     for(auto v : vec) {
        std::visit([](auto&& arg) {
          using T = decltype(arg);
          // if (std::is_same_v<std::remove_reference<T>, int>) {
          if (std::is_same_v<T, int&>) {
            cout<<"int "<<arg<<endl;
          }
        }, v);
      }
     return 0;
   }

Now if i apply std::remove_reference, it doesn’t print. In fact, it doesn’t matter if I use int, int& or int&&, cout doesn’t get printed

 #include <vector>
 #include <sys/types.h>
 using namespace std;
 using var_t = std::variant<int, long, double, std::string>;
 int main(int argc, char* argv[]) {
    std::vector<var_t> vec = {10};
    for(auto v : vec) {
       std::visit([](auto&& arg) {
         using T = decltype(arg);
         if (std::is_same_v<std::remove_reference<T>, int>) {
           cout<<"int "<<arg<<endl;
         }
       }, v);
     }
  return 0;
 }

Why is this happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s a typo, but fascinating enough to answer: you forgot _t to extract the type from std::remove_reference.

if (std::is_same_v<std::remove_reference_t<T>, int>) {
//                                      ^~

Why does it compile? Well, std::remove_reference is also a class. It’s perfectly fine thing to pass as std::is_same template argument, so the compiler doesn’t object. But what you really want is the type member of this class (which is also conveniently provided as _t alias).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading