I have a class like this:
template <unsigned int A, unsigned int B>
class Foo { ... };
Foo needs a method called bar(), but I need to specialise this. For a case, when A == B, I want it to do a thing, and something else otherwise. Can I do this without writing an if statement into the function? Like:
Foo<A, A>::bar() { ... } and Foo<A, B>::bar() { ... }
You can partially specialize your class:
#include<cassert>
template<typename A, typename B>
struct S {
void f(int i) { assert(i == 42); }
};
template<typename A>
struct S<A, A> {
void f(int i) { assert(i == 0); }
};
int main() {
S<int, double> s1;
S<int, int> s2;
s1.f(42);
s2.f(0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With