Transfer between constant char * [] [3] and std :: array <const char *, 3> *

I need a way to throw between these two types of variables:

std::array< const char*, 3 >* foo;
const char* foo[][3];

Because I need to be able to pass both types to a function. A function can be defined in any of these ways, depending on what simplifies the conversion:

void bar( std::array< const char*, 3 >* param );
void bar( const char* param[][3] );

In this question, Jarod42 suggests using the method here . Is there a cleaner way to do this?

Change in response to dyp link

This one reinterpret_castreally worked for me, but Ivan Shcherbakov describes it as an “ugly dirty hack” that I inserted into the code below ... I don’t understand why this hack, or why something might go wrong with this? Is the template method proposed by Nathan Monteleone necessarily better than this?

void bar( std::array< const char*, 3 >* param ){}

void main( void )
{
    static const char* cStyle[][3] = { NULL };
    std::array< const char*, 3 > foo = { NULL };
    std::array< const char*, 3 >* stlStyle = &foo;

    bar( reinterpret_cast< std::array< const char*, 3 >* >( cStyle ) );
    bar( stlStyle );
}
+4
source share
2 answers

Based on Nathan Monteleone solution :

template < typename T >
void bar( T* param )
{
    static_assert( 3 == ( std::is_array< T >::value ? std::extent< T >::value : std::tuple_size< T >::value ), "param must have a size of 3" );
}

I believe that this solution is the best of all worlds, because it allows you to avoid reinterpret_castimplementation-dependent. And it guarantees that it paramshould be size 3 at compile time.

+1
source

, , .

template <class T> void Tbar( T param ) {
    char c12 = param[1][2];    // (for example)
}

, [3]. , - , , cpp

void bar( std::array< const char*, 3 >* param ) { Tbar(param); }
void bar( const char* param[][3] ) { Tbar(param); }

, . , , , , Tbar, : , char*[][3], array<char*, 3>*. , , , Tbar .

+2

Source: https://habr.com/ru/post/1533603/


All Articles