[Please do not mail me a copy of your followup]
Doug Mika <
doug...@gmail.com> spake the secret code
<
53029355-0634-49cf...@googlegroups.com> thusly:
Ask yourself "What does static_assert do?"
Answer: "Performs compile-time assertion checking."
<
http://en.cppreference.com/w/cpp/language/static_assert>
What does this imply? It implies that the arguments to static_assert
must be evaluated at compile-time and not at runtime.
What are the arguments to static_assert?
1. 100000<numeric_limits<int>::max() aka
100000 < numeric_limits<int>::max()
2. "small ints!"
The 2nd argument is just the diagnostic message to be printed when the
static assertion fails. The first argument must be something that can
be evaluated at compile-time, so let's look at it more carefully.
It is an application of operator< to 100000 and
numeric_limits<int>::max(). 100000 is a constant, so no problem there.
numeric_limits<int>::max() is an invocation of the max member function
on the class numeric_limits<int>. numeric_limits<int> is known at
compile time, so no problem there. All that's left is the max member
function. This function must be declared constexpr so that it can be
evaluated at compile time, otherwise it would be a compilation error.
template <typename T>
struct foo
{
T max();
};
template<>
struct foo<int>
{
static int max() { return 10; }
};
static_assert(100000 < foo<int>::max(), "whoops");
g++ -c -g -std=c++0x /tmp/a.cpp
/tmp/a.cpp:13:1: error: non-constant condition for static assertion
static_assert(100000 < foo<int>::max(), "whoops");
^
/tmp/a.cpp:13:38: error: call to non-constexpr function 'static int
foo<int>::max()'
static_assert(100000 < foo<int>::max(), "whoops");
^
We can fix this by making the function constexpr, allowing the compiler
to use it at compile time:
template <typename T>
struct foo
{
T max();
};
template<>
struct foo<int>
{
static constexpr int max() { return 10; }
};
static_assert(100000 < foo<int>::max(), "whoops");
g++ -c -g -std=c++0x /tmp/a.cpp
/tmp/a.cpp:13:1: error: static assertion failed: whoops
static_assert(100000 < foo<int>::max(), "whoops");
^
--
"The Direct3D Graphics Pipeline" free book <
http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <
http://computergraphicsmuseum.org>
The Terminals Wiki <
http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <
http://legalizeadulthood.wordpress.com>