Jump to content
  • Advertisement
Sign in to follow this  
widggman

checking template type or value

This topic is 3759 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a simple question, but I think the answer is "No!" but I will ask it. With a template in C++, is it possible to check the value or the type in a template with the preprocessor ?? Ex.: I use an integer in a template but that integer should have a minimum value or should be in a range or whatever. Here what I would like to do: template<int N> void function(param1, param2, ..., paramN) { #if N < 3 #error "N should be greater or equal to 3" #endif // rest of the function } But I have to do something like this: template<int N> void function(param1, param2, ..., paramN) { if (N < 3) throw exception("N should be greater or equal to 3"); // rest of the function } In the first one, it's at compiled time (even if it doesn't work)... and the second, is at the execution. Is there a way to do this at compiled time ? And it's the same thing for the type using "typeid". And if it doesn't exist, it could be a nice feature to add!

Share this post


Link to post
Share on other sites
Advertisement
Excluding boost for a second:


template < class bool >
struct Assert {
};

template < >
struct Assert<false>
{
Literal test will cause compile-time error
};




template<int N>
void function(param1, param2, ..., paramN)
{
Assert<(N>2)> test;
}




This approach will result in no run-time code, and if N < 3 will fail to compile.

Share this post


Link to post
Share on other sites
I tried it, and with G++ whatever I do, it doesn't stop the compilation. What should I put in the struct Assert<false>. A message ??

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!