weno
weno

Reputation: 856

Specializing only one method of a class template

I have a class template that works correctly for all possible types T1, T2.

template <typename T1, typename T2>
class Basic {
    int a;
    float b;

public:
    void foo(T1 t1, T2 t2) {
        // use a, b, t1, t2
    }
};

However, there is one case when T2 is char, and I expect foo to behave differently.

So I tried specializing only that method:

template <typename T1>
class Basic<T1, char> {
    void foo(T1 t1, char t2) {
        // try using a, b, t1, t2 in a very special way

        // ERROR:
        // use of undeclared identifier: a
        // use of undeclared identifier: b
    }
};

Problem is, there are potentially a lot of different data members and methods in the template class Basic, that are not necessarily related to the function foo.

That being said, I feel like full class specialization would be a bloat. Is there a better solution?

Upvotes: 1

Views: 67

Answers (2)

cigien
cigien

Reputation: 60218

You can use std::is_same to do something else in foo, when T2 is char:

void foo(T1 t1, T2 t2) {
   if (std::is_same<T2, char>::value)
     std::cout << "char";
   else
     std::cout << "not char";
}

You don't need a full specialization of Basic for this, or even a specialization for foo.

Here's a demo.

From c++17, you can even avoid compiling the branch that is not needed, (i.e. compile the char branch only when T2 is char, and vice-versa), using if constexpr, like this:

if constexpr (std::is_same<T2, char>())

Here's a demo.

Upvotes: 2

Nelfeal
Nelfeal

Reputation: 13269

You can branch with std::is_same<T2, char>, like if (std::is_same<T2, char>::value), or you can use tag-dispatching, like this:

public:
    void foo(T1 t1, T2 t2) {
        foo_impl(t1, t2, std::is_same<T2, char>{});
    }

private:
    void foo_impl(T1 t1, T2 t2, std::false_type) {
        std::cout << "T2 != char\n";
    }

    void foo_impl(T1 t1, T2 t2, std::true_type) {
        std::cout << "T2 == char\n";
    }

Demo

Upvotes: 1

Related Questions