简体   繁体   中英

Not compile time constant

I have:

    static const std::array<std::pair<ServerD, unsigned int>, 4> dataSizes =
{ std::make_pair(ServerD::ContentType, 1)
, std::make_pair(ServerD::RemoteAddress, 2)
, std::make_pair(ServerD::RemoteUser, 3)
, std::make_pair(ServerD::Url, 4)
};

template <unsigned int Index>
struct SizeFinder {
    static const unsigned int SizeFor(ServerD data) {
        return (dataSizes[Index].first == data) ? dataSizes[Index].second :
            SizeFinder<Index - 1>::SizeFor(data);
    }
};

template <>
struct SizeFinder<0> {
    static const unsigned int SizeFor(ServerD data) {
        return (dataSizes[0].first == data) ? dataSizes[0].second :
            0;
    }
};

Why is this not a compile time constant:

char tst[SizeFinder<4>::SizeFor(serverD)]

// Error 1 error C2975: 'BufferSize' : invalid template argument for 'isapi::`anonymous-namespace'::GetVariableFor', expected compile-time constant expression

I must make this work without constexpr. VS2013 still does not have this.

EDIT As it seems static const functions cannot compute at compile time, is there a workaround for C++ 03 ?

It would appear that you simply need a compile-time mapping from ServerD to unsigned int . Why not embed it in the enumeration values:

enum class ServerD : unsigned int {
    ContentType = 1U,
    RemoteAddress = 2U,
    RemoteUser = 3U,
    Url = 4U
};

char tst[ServerD::Url];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM