Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce templated class arguments in C++

Tags:

c++

templates

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() { ... }
like image 326
Peter Lenkefi Avatar asked Feb 07 '23 02:02

Peter Lenkefi


1 Answers

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);
}
like image 135
skypjack Avatar answered Feb 20 '23 00:02

skypjack