I have a C++ 03 class with a header only implementation. The class uses a static null vector shared among all classes:
static const byte nullVector[64];
When I initialized outside the class, linking failed due to duplicate symbols. So I moved it into a function and made is a static local according to How to have static data members in a header-only library?
Now I am trying to return that byte array from the accessor:
static const byte[64]& GetNullVector {
static const byte s_NullVector[64] = {
0,0,0,0,0,0,0,0, ... 0,0,0,0,0,0,0,0
};
return s_NullVector;
}
While it might look odd trying to return a byte[]&, I need it because of a compile time assert:
COMPILE_ASSERT(DIGEST_SIZE <= COUNTOF(GetNullVector()));
The COUNTOF macro needs a real array, and it fails on pointers. It worked fine when the byte array was a static class member.
How do I return a reference to the byte array, complete with its size so diagnostics continue to work as expected, under C++03?
Thanks in advance.
Here's what the compile error looks like. Both return types of static const byte[64] and static const byte[] produce the error.
c++ -DNDEBUG -g2 -O3 -fPIC -march=native -pipe -c validat3.cpp
In file included from validat3.cpp:16:
./hkdf.h:33:19: error: expected member name or ';' after declaration specifiers
static const byte[]& GetNullVector {
~~~~~~~~~~~~~~~~~^
./hkdf.h:58:49: error: use of undeclared identifier 'GetNullVector'
COMPILE_ASSERT(DIGEST_SIZE <= COUNTOF(GetNullVector()));
The syntax for C arrays sort of wraps around the identifier it's attached to (e.g. int array[64]).
When you bring references into it, it gets a little uglier:
int (&array_ref)[64]
and now if you want to return such a reference from a function:
int (& GetNullVector())[64] { ... }
However with some typedefs, you can avoid having to explain this ugly declaration in the next code review ;)
typedef byte null_vec_t[64];
static const null_vec_t& GetNullVector()
{
static const null_vec_t s_NullVector = {0};
return s_NullVector;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With