0

I have this structure:

struct S_SPECIAL_EVENT
{
    BOOL            bEventAllDay{};

    friend CArchive& operator<<(CArchive& rArchive, S_SPECIAL_EVENT const& rsSE)
    {
        const WORD wVersion = 1;
        return rArchive << wVersion
            << gsl::narrow<bool>(rsSE.bEventAllDay);
    }

    friend CArchive& operator>>(CArchive& rArchive, S_SPECIAL_EVENT &rsSE)
    {
        WORD wVersion{};

        rArchive >> wVersion;
        rsSE.bEventAllDay = readAndCast<BOOL, bool>(rArchive);

        return rArchive;
    }
};

I tried adding the two serialize operators. But I get compile errors like:

error C3861: 'readAndCast': identifier not found

The method in question is defined in the application header:

// See: https://stackoverflow.com/a/58746336/2287576
template <typename T, typename U>
T readAndCast(CArchive& ar) {
    U x;
    ar >> x;
    return static_cast<T> (x);
}

I have included that header in my file. So why won't it complile?


I changed my code to do things manually:

friend CArchive& operator>>(CArchive& rArchive, S_SPECIAL_EVENT &rsSE)
{
    WORD wVersion{};
    bool bData{};

    rArchive >> wVersion;
    rArchive >> bData;
    rsSE.bEventAllDay = gsl::narrow<BOOL>(bData);

    return rArchive;
}

But I would like to know the answer to the original question.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • 1
    Can you reduce this to a minimal, reproducible example, that doesn't rely on numerous type and enum definitions that you have not provided? – Adrian Mole Nov 13 '22 at 11:27
  • 1
    Can't reproduce. Maybe there's an issue with the order of header includes? (Like the template not seeing the correct definition of `CArchive`?) – Adrian Mole Nov 13 '22 at 11:49
  • @AdrianMole OK, probably that then ... – Andrew Truckle Nov 13 '22 at 11:51
  • @AdrianMole I think it is because the app class header file #includes the header file that defines the structure / operator. It is further down in the app header file that we define the readAndCast method. – Andrew Truckle Nov 13 '22 at 13:41
  • Yep. That would cause the error you've cited. – Adrian Mole Nov 13 '22 at 13:46
  • @AdrianMole I could move the definition of readAndCast to before the header inclusion I guess but I don't like that idea. – Andrew Truckle Nov 13 '22 at 13:48
  • 1
    Well, one way or another, you *have* to make sure that your definition of `readAndCast` is seen before you use it. If that's a function template that you use widely in your code, then it *should* be near the top of your 'global' header(s) and (long) before any specialisations of it are instantiated. – Adrian Mole Nov 13 '22 at 13:54
  • where did you add the #include ? If you add it before the stdafx.h or pch.h #include, then it won't be looked at. You need to include it after the precompiled header's #include. – Ed Dore Nov 14 '22 at 17:39

0 Answers0