mercredi 26 octobre 2016

C++ implement my own static_assert

As a learning project, I'm writing my own template metaprogramming static_assert. I found a metaprogramming trick online: try to create an array of size 0, which will fail to compile. So I'm using two nearly identical approaches: on Visual Studio, one works and the other doesn't, but I don't understand what's the difference. On g++ 5.4.0, neither works (not even with the "-std=c++14" flag). Why not?

//This correctly aborts the compile on Visual Studio 2015. 
//But on g++ it doesn't work (not even with the "-std=c++14" flag) .
template <bool b>
inline void my_static_assert_function()
{
    char member[b]; //if b is false, this is 0-length and fails to compile. 
}

//On Visual Studio 2015, this does give a warning, but does not
//abort the compile. Why not? It seems virtually identical to the
//previous one. And on g++, it doesn't even warn. 
template <bool b>
struct my_static_assert_struct
{
    char member[b]; //if b is false, this *warns* but compiles.
};

int main()
{
    my_static_assert_function<1 == 2>(); //This aborts the compile, great.
    my_static_assert_struct<1 == 2> c; //This does NOT abort the compile???
}

Question #1 -- why does "g++ -std=c++14 main.cpp" allow this to compile without even a warning? Shouldn't the my_static_assert_function work there? I'm using 5.4.0 for ubuntu.

Question #2 -- on Visual Studio 2015, my_static_assert_function fails to compile, but my_static_assert_struct compiles with a mere warning. But what's the difference? How can one work if the other doesn't?

Aucun commentaire:

Enregistrer un commentaire