Joey
Joey

Reputation: 122

C++, Perform Preprocessor logic on Template Arguments

I would like to do something like this:

#define _FLAT_TOP 1
#define _FLAT_BOTTOM 2

template <int TYPE>
void myFunction() {

 #if TYPE == _FLAT_TOP

       int pixelTop = 453;

 #elif TYPE == _FLAT_BOTTOM

       int pixelTop = 990;

 #endif

     // code that uses pixelTop

}

And then be able to call the function like so

myFunction<_FLAT_TOP>();

However, neither of the #if statement blocks are being compiled (they are both grayed out in Visual Studio and the code that uses pixelTop after is red underlined). The reason I don't want to use a regular if statement is because there is actually way more going on in that function than I wrote and using if statements during run time causes noticeable performance drops. I need to know if what I am trying to do here is possible and if so how to do it?

Upvotes: 0

Views: 41

Answers (2)

catnip
catnip

Reputation: 25388

In C+17 and later, you can use if constexpr:

#define _FLAT_TOP 1
#define _FLAT_BOTTOM 2

template <int TYPE>
void myFunction() {
    int pixelTop = 0;
    if constexpr (TYPE == _FLAT_TOP)
       pixelTop = 453;
    else if constexpr (TYPE == _FLAT_BOTTOM)
       pixelTop = 990;

    // do something with pixelTop
}

Note that pixeltop needs to be declared above the if statements to still be in scope when you want to 'do something' with it.

Upvotes: 2

john
john

Reputation: 87932

Template specialization?

template <int TYPE>
struct pixelTop {
    // no default value
};

template <>
struct pixelTop<_FLAT_TOP> {
    static const int value = 453;
};

template <>
struct pixelTop<_FLAT_BOTTOM> {
    static const int value = 990;
};

template <int TYPE>
void myFunction() {

       int pixelTopValue = pixelTop<TYPE>::value;
       ...    
}

Added bonus that if TYPE is something other than the two specialized values you'll get a compiler error.

Upvotes: 1

Related Questions