Is there a way to make a template function apply to an array of any length in C ++?

I have a situation where I need to read a text file and check if a mnemonic is valid, so I have a dynamic set of mnemonics (currently 1226!) That I can change later when needed. So I tried this way first:

enum InstrID
{
    I_INVALID = 0,

    I_AAA,
    I_AAD,
    ...
};

static char const * nameOfinstrID[] =
{
    "???",

    "AAA",
    "AAD",
    ...
};


struct InstrIDIterator
{
    template< int N > static InstrIDIterator Make(char const * begin[N], size_t index = N)
    {
        InstrIDIterator result;
        result.index = index;
        result.begin = begin;
        return result;
    }

    std::map< std::string, InstrID >::value_type operator * () { return std::map< std::string, InstrID >::value_type(begin[index], InstrID(index)); }

    ... // iterator-like stuff

    size_t index;
    char const ** begin;
};

InstrID getInstrID(std::string const & name)
{
    static std::map< std::string, InstrID > instrID_map(InstrIDIterator::Make(nameOfinstrID, 0), InstrIDIterator::Make(nameOfinstrID));

    return instrID_map[name];
}

...

      

But I got this error in MSVC 2013:

error C2784: 'x86_text_grammar :: InstrIDIterator x86_text_grammar :: InstrIDIterator :: Make (const char * [N], size_t)': Could not deduce template argument for 'const char * [N]' from 'const char * [1225]'

So my question is, is this a problem only regarding MSVC 2013? or is this something normal even for ISO C ++ x11?

Of course, in this case, I can proceed with a more general way of compiling (and better for checking the size of an array of strings):

enum InstrID
{
    I_INVALID = 0,

    I_AAA,
    I_AAD,
    ...
    InstrID_max
};

static char const * nameOfinstrID[InstrID_max] =
{
    "???",

    "AAA",
    "AAD",
    ...
};

struct InstrIDIterator
{
    static InstrIDIterator Make(char const * begin[InstrID_max], size_t index = InstrID_max)
    {
        InstrIDIterator result;
        result.index = index;
        result.begin = begin;
        return result;
    }

    ...
};

      

+3


source to share


1 answer


The functional parameter of the form has been changed T[N]

(i.e. it is actually exactly the same) T*

. Thus, the parameter is the char const * begin[InstrID_max]

same as the parameter char const** begin

.

You can use a reference to an array of a specific size as a parameter with the syntax T (&array_name)[ARRAY_LENGTH]

. This leaves you with



template<size_t N>
static InstrIDIterator Make(const char* (&begin)[N],  size_t index = N);

      

+8


source







All Articles