mercredi 12 juillet 2023

In C++ 11 Is there any way to branch by if a function parameter is compile-time constant or not?

Is there anyway I can tell function argument is compile time-constant or not in C++ 11?. I would like to branch the functions body based on the results. For example, like below;

template <T>
size_t get_length(const T &t)
{
    return t.size();
}

template <typename T, size_t N>
size_t get_length(const std::array<T, N> &t)
{
    return N;
}

// Maybe some template
??? foo(size_t length)
{
    ...
    // If length could be evaluated at compile time,
    return std::array<int, length>{};

    ...
    // Otherwise,
    return std::vector<int>(length);
}


// ??? and auto should be std::array if bar is std::array, std::vector if bar is std::vector or etc.
auto x = foo(get_length(bar));

I believe this need two task; First it should be able to determine if a value is compile time evaluable or not. Second, convert a value to compile time constant if possible.

Is there anyway one can do this? Or is there any reason this is impossible? It seems some say to use template function, but that forces caller to put compile time constant and not what I am looking for.

Aucun commentaire:

Enregistrer un commentaire