What is the proper syntax for std::get_if on a std::shared_ptr< std::variant<...> >?

The following code is pretty self explanatory, I'm getting some compiler errors when trying to compile it. Do you know what changes I need to make to get this to compile? I've simplified the example, so you don't have to do too much reading.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <memory>
#include <variant>

using namespace std;

int main( int argc, char *argv[] ){
  using IntOrChar = variant< int, char >;
  shared_ptr< IntOrChar > value( new IntOrChar( (int)1 ) );
  if( auto i = get_if< int >( *value ) )
    cout << i << endl;
}


The previous code doesn't compile for some reason, and yet the following does:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <memory>
#include <variant>

using namespace std;

int main( int argc, char *argv[] ){
  using IntOrChar = variant< int, char >;
  shared_ptr< IntOrChar > value( new IntOrChar( (int)1 ) );
  if( holds_alternative< int >( *value ) )
    cout << get< int >( *value ) << endl;
}


I'd rather use std::get_if, if I can, because it's less lines of code for what I'm programming, and holds_alternative is a long function name.

Thanks for any help.
Last edited on
std::get_if takes a pointer to a variant.

-Albatross
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <memory>
#include <variant>

using namespace std;

int main(){
  using IntOrChar = variant< int, char >;
  shared_ptr< IntOrChar > value( new IntOrChar( (int)1 ) );
  if( auto i = get_if< int >( value.get() ) )
    cout << *i << endl;
}

Thanks TheDaemoness and dutch, that's compiling for me, and cout'ing the correct value for i.
Topic archived. No new replies allowed.