#Expressing variable sized const char* array using std::array

20 messages · Page 1 of 1 (latest)

sudden ether
#

Hi, I have the following the following piece of code:

    const char* known_extensions[] = {
      ".mia",
      ".mib",
      ".mic",
#ifdef TIFF_SUPPORT
      ".tiff",
      ".tif",
      ".TIFF",
      ".TIF",
#endif
#ifdef PNG_SUPPORT
      ".png",
      ".PNG",
#endif
      nullptr
    };

Is there a way to express this using std::array ? I'd like an easy to way to evaluate the size of the array depending on whether those macros are actually defined.

upbeat lintelBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

tired flame
#

;compile

#include <array>
    std::array known_extensions {
      ".mia",
      ".mib",
      ".mic",
#ifdef TIFF_SUPPORT
      ".tiff",
      ".tif",
      ".TIFF",
      ".TIF",
#endif
#ifdef PNG_SUPPORT
      ".png",
      ".PNG",
#endif
    };

int main(){}
steady obsidianBOT
#
Compilation successful

No output.

tired flame
#

There we go

sudden ether
#

Ah ok nice. Didn't know that you could get away without specifying size

tired flame
#

In c++17 and onward, you don't have to specify template argument if they can be inferred from the constructor arguments

sudden ether
#

Brilliant!

sudden ether
#

Is there a way to determine the type induced by the compiler though? Ideally I would like the array above to be a std::arraystd::string

tired flame
#

Hmmm, that one might be more tough

sudden ether
#

I guess the easiest way would be to just wrap the strings with std::string

tired flame
#

;compile

#include <array>
#include <string>

using namespace std::string_literals;

    std::array known_extensions {
      ".mia"s,
      ".mib"s,
      ".mic"s,
#ifdef TIFF_SUPPORT
      ".tiff"s,
      ".tif"s,
      ".TIFF"s,
      ".TIF"s,
#endif
#ifdef PNG_SUPPORT
      ".png"s,
      ".PNG"s,
#endif
    };

int main(){}
steady obsidianBOT
#
Compilation successful

No output.

tired flame
#

I prefer using the string literal namespace here

sudden ether
#

Yes, I guess that's a little nicer.

kind falcon
#

you can also ensure that the inferred type is correct using type traits:

#

;compile --std=c++20

#include <array>
#include <string>
#include <type_traits>

using namespace std::string_literals;

    std::array known_extensions {
      ".mia"s,
      ".mib"s,
      ".mic"s,
#ifdef TIFF_SUPPORT
      ".tiff"s,
      ".tif"s,
      ".TIFF"s,
      ".TIF"s,
#endif
#ifdef PNG_SUPPORT
      ".png"s,
      ".PNG"s,
#endif
    };

static_assert(std::is_same_v<decltype(known_extensions)::value_type, std::string>);

int main(){}
steady obsidianBOT
#
Compilation successful

No output.

kind falcon
#

(if you want to be sure it does the thing you want it to do

sudden ether
#

!solved