1

So I have an array of structures and a class that uses the array. The constructor needs to reference the array of structures which are a constant. What I am struggling with is passing the array of structures as a reference so that the class constructor can use it. Since the array of structures doesn't change there is no need to copy it, I just need to reference it. Here is my current code which generates errors.

struct c_cs_pair_t
{
    const wchar_t c;
    const wchar_t* cs;
};


class Converter
{
protected:
    size_t  _length;
    const c_cs_pair_t(& _pairs)[];

public:

    Converter ( const c_cs_pair_t(& pairs)[] ) : _pairs(pairs) {
        _length = sizeof ( pairs ) / sizeof( c_cs_pair_t );
    }

};

const c_cs_pair_t c2cspairs[] = 
        { { L'\n', L"\\n" }
        , { L'\0', L"\\0" }
        , { L'\\', L"\\\\" }
        , { L'[', L"\\[" }
        , { L']', L"\\]" }
        , { L'.', L"\\." }
        , { L':', L"\\:" }
        , { L'\u0008', L"\\b" }
        , { L'\u000c', L"\\f" }
        , { L'\u000a', L"\\n" }
        , { L'\u000d', L"\\r" }
        , { L'\u0009', L"\\t" }
        , { L'\u000b', L"\\v" }
        , { L'\u0000', L"\\0" }
        };

const Converter converter ( c2cspairs );

When I compile I get compilation errors complaining there is no matching candidate.

How do I pass the array to the constructor so the class methods can use it. The array knows it's size implicitly as it is a constant.

2

1 Answer 1

5

You need to specify the size of the array using a template parameter:

template<size_t N>
class Converter
{
protected:
    size_t  _length;
    const c_cs_pair_t(& _pairs)[N];

public:
    Converter ( const c_cs_pair_t(& pairs)[N] ) : _pairs(pairs) {
        _length = N;
    }
};

Note that you don't really need the _length member any longer.

Here's a demo. Note that this only works from c++17 with the introduction of class template argument deduction.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.