I’m trying to trigger a compile time error if the user of my library tries to instantiate a template with a type that is not appropriate. I’ve implemented:
template <typename T>
struct good_type { enum { value = false }; };
template <>
struct good_type<string> { enum { value = true }; };
template <>
struct good_type<int64_t> { enum { value = true }; };
template <typename T>
struct X
{
BOOST_STATIC_ASSERT(good_type<T>::value);
};
int main(int argc, char** argv)
{
X<string> x1;
X<int64_t> x2;
X<float> x3;
return 0;
}
which works, but the message I get from gcc is a bit surprising:
error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>'
Should I be using a different Boost macro? Is there a better way to do this?
Thanks!
You can use
boost::enable_if, along with typelist.Define a typelist which contains all the types which you want to support, and write some metafunction(s), to check if a given type exists in the list or not, and then pass the value which metafunction returns to
enable_if, so as to enable/disable the class.Alright, I wrote a code for demo. Its not using
boost::enable_ifthough (that is for you to experiment with).Here is the framework first:
—
Now follows the testing code:
which compiles perfectly fine (ideone), and gives this output (for the
coutstatements):But if you uncomment the line
X<long> x2;in the above code, it will not compile, sincelongis an unsupported type. And it gives this error, which is easy to read and understand (ideone):Hope this helps you.
Now you can write a class template called
enable_if_supportedwhich takes two type arguments:Tandsupported_types. You can derive your class fromenable_if_supportedas:This looks a bit clean.
enable_if_supportedclass template now is defined in the framework section. See it here working : http://www.ideone.com/EuOgc