const char*[] [3]和std :: array <const char*,3>*之间的转换

Jon*_*Mee 5 c++ arrays dynamic-arrays

我需要一种方法来在这两种类型的变量之间进行转换:

std::array< const char*, 3 >* foo;
const char* foo[][3];
Run Code Online (Sandbox Code Playgroud)

因为我需要能够将两种类型都传递给函数.可以通过以下方式定义函数,无论哪种方式使转换更容易:

void bar( std::array< const char*, 3 >* param );
void bar( const char* param[][3] );
Run Code Online (Sandbox Code Playgroud)

这个问题中,Jarod42建议在这里使用这个方法.有更清洁的方法吗?

编辑以响应dyp链接

reinterpret_cast确实对我有用,但Ivan Shcherbakov将其描述为"丑陋的黑客",我粘贴了代码,下面......我不明白为什么这是一个黑客,或者为什么会出现问题呢?Nathan Monteleone建议的模板方法一定比这更好吗?

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 );
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*Mee 2

基于Nathan Monteleone的解决方案:

template<typename T>
enable_if_t<conditional_t<is_array_v<T>, extent<T>, tuple_size<T>>::value == 3U> bar(T* param){}
Run Code Online (Sandbox Code Playgroud)

我相信这个解决方案是世界上最好的解决方案,因为它避免了reinterpret_cast依赖于实现的问题。并且它强制param在编译时大小必须为 3。

请注意,conditional_t仅在选择类型后才会调用 的值。有关更多信息,请参阅:enable_if 中的短路运算符

Live Example


归档时间:

查看次数:

1145 次

最近记录:

7 年,4 月 前