Sign in to follow this  

Preprocessor Comparison of Templated Parameter

This topic is 3312 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
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 [code] and [quote] 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

This topic is 3312 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this