Jump to content
  • Advertisement
Sign in to follow this  
ndwork

Preprocessor Comparison of Templated Parameter

This topic is 3647 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 am attempting to use the preprocessor to compile different code based on a templated parameter. The code is below.
template <int A>
class testClass{
public:
  testClass(){
    cout << A << endl;
    #if A >= 5
      cout << "Greater than 5" << endl;
    #else
      cout << "Less than 5" << endl;
    #endif
  }
};

int main( ){
  testClass<8>();
  testClass<1>();
}


The output from this code is
Quote:
8 Less than 5 1 Less than 5
I'm aware that I could use a regular if statement to conduct the comparison, but I seek the speed advantage of avoiding that comparison by conducting the comparison at compile time rather than run time. Can you use the preprocessor to conduct comparisons with templated parameters? If not, how can I compile different code based on a templated parameter?

Share this post


Link to post
Share on other sites
Advertisement
The handling of preprocessor commands occurs before templates are even parsed. The only A your #if will check are the ones that have been #define-d.

Also, your compiler is not dumb. Since template parameters cannot change, it already eliminates the other branch of the conditional. It may even cause spurious warnings that your if-condition always evaluates to true (or false). No speed will be lost by using a normal if in this situation.

Finally, the slashes on and
tags go the other way. You may also find yourself prefering [ source ] tags for anything more than 2 or 3 lines, as they do syntax highlighting and scrolling.

Share this post


Link to post
Share on other sites
One possibility is to use template specialization (in one or another way). For example, to make your code produce expected output, something like that:


#include <iostream>

template <bool b>
struct testClassImp
{};

template <>
struct testClassImp<true>
{
testClassImp() { std::cout << "Greater than 5\n"; }
};

template <>
struct testClassImp<false>
{
testClassImp() { std::cout << "Less than 5\n"; }
};

template <int A>
class testClass : public testClassImp<(A >= 5)>{
};

int main( ){
testClass<8>();
testClass<1>();
}

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!