I usually use std::size_twhere integral constants are required in the template parameters. However, I noticed that the type system does not protect me from users who are happy to pass negative numbers as arguments to these parameters.
For example, the following compilations giving catastrophic results:
#include <iostream>
template<std::size_t I>
struct E1
{
static void apply()
{
std::cout << I << std::endl;
}
};
template<typename T>
constexpr T a = T { -1 };
template<std::size_t... Is>
void E2()
{
for (auto&& i : {Is...}) std::cout << i << " ";
std::cout << std::endl;
}
int main()
{
E1<-1>::apply();
E2<-1, -2, -3>();
}
Interestingly, this is not allowed for template variables (uncommenting the last line in maincauses a compilation error).
Is there any solution / workaround for case structand function?
source
share