I am new to this message-board so if there is anything wrong with this question please feel free to correct me.
Currently I am rewriting/extending my C++ utility library taking new C++11 features into account. One of the new additions is a template class which gives the maximum value of a set of numbers, hopefully at compile time.
template<typename T, T... Xs> class ConstMax
{
private:
template<typename... Ts> static constexpr T Max(Ts... xs);
template<typename Tx> static constexpr T Max(Tx x)
{
return x;
}
template<typename T1, typename T2, typename... Ts> static constexpr T Max(T1 x, T2 y, Ts... xs)
{
return y > x ? Max<T2, Ts...>(y, xs...) : Max<T1, Ts...>(x, xs...);
}
public:
static const T Value = Max(Xs...);
};
An example use of this class:
int max = ConstMax<int, 1, 8, 66, 32, 90, 12, 33>::Value;
Here another example which might make it harder to verify if ConstMax<...>::Value was actually evaluated during compile time:
template<typename... Ts> class Variant
{
public:
static const size_t MaxValueSize = ConstMax<size_t, sizeof(Ts)...>::Value;
};
Which results in max = 90. I stepped trough this code using gdb and it seems there is no function call executed during the assignment of max.
My questions:
- Can I safely assume that ConstMax<...>::Value is always known at compile time?
- Is there a way to check if constexpr functions/methods are evaluated at compile time?
- I understand members/methods/functions defined as constexpr are not necessarily evaluated during compile time, does the fact that Value is defined as being static const change anything about this or am I better off implementing this specific case as a recursive template class?
Aucun commentaire:
Enregistrer un commentaire