The use of std::launder
as suggested by @user2079303 is a good option if you are sure that value does indeed point to an array of the right size as mentioned in their answer.
Yet another approach: since SIZE
is fairly small in this case, it may be safer/simpler to create a temporary copy of value
and pass it to DoSomething()
. But it all depends on what DoSomething()
is actually doing (for example, does it modify the array passed to it). For example:
#include <iostream>
#include <vector>
#include <string>
constexpr int SIZE = 16 ;
void DoSomething(char (&value)[SIZE])
{
std::cout << "Do it!" << std::endl ;
}
void BeforeDoingSomething(char* value, int len)
{
if (len == SIZE)
{
char tmp_array[SIZE] ;
std::copy(value, value + len, tmp_array) ;
DoSomething(tmp_array);
} else {
std::cout << "Length: " << len << std::endl ;
}
}
int main()
{
std::string foo (SIZE, '-') ;
BeforeDoingSomething(foo.data(), foo.size()) ;
std::vector<char> bar (SIZE) ;
BeforeDoingSomething(bar.data(), bar.size()) ;
std::string qux ;
BeforeDoingSomething(qux.data(), qux.size()) ;
return 0 ;
}
Try it online here.