1

Is there any way to call a class member function that takes only 1 template argument instead of 2?

I would like to write some code like this:

template<typename T, size_t N>
void Container<int, N>::quick_sort() {

}
Shope
  • 11
  • 1
  • 1
    Why not `template void Container::quick_sort() { }` – Thomas Sablik Jun 11 '20 at 14:10
  • @ThomasSablik template argument list must match the parameter list – Shope Jun 11 '20 at 14:13
  • If you intend to have a special sorting algorithm for `int`-s, then use *tag-dispatching* – Piotr Skotnicki Jun 11 '20 at 14:27
  • 2
    There is a lot of context missing here, but your template arguments are not for the function, they are for the class. Do you want a special function for containers of `int`? – molbdnilo Jun 11 '20 at 14:28
  • @molbdnilo Yes exactly – Shope Jun 11 '20 at 15:04
  • Related to [partial-template-specialization-for-constructor](https://stackoverflow.com/questions/61992005/partial-template-specialization-for-constructor) and [partial-specialization-for-one-method-in-the-class](https://stackoverflow.com/questions/61795331/partial-specialization-for-one-method-in-the-class) – Jarod42 Jun 11 '20 at 19:42

1 Answers1

0

You cannot partial specialize a method, you could partial specialize the whole class, but require some duplication.

template<typename T, size_t N>
class Container
{
    // Some code ...
    void quick_sort();
};

template <typename T,size_t N>
void Container<T, N>::quick_sort()
{
   // ...
}

// Class specialization
template <size_t N>
class Container<int, N>
{
    // Some similar/same code...
    void quick_sort();
};

template <size_t N>
void Container<int, N>::quick_sort()
{
   // ...
}

As alternative, C++17 allows

template<typename T, size_t N>
class Container
{
    // Some code ...
    void quick_sort()
    {
        if constexpr (std::is_same_v<int, T>) {
            // ...
        } else {
            // ...
        }
    }

};

For prior versions, regular if would probably produces error (both branches should be valid, even if not taken).

So tag dispatching is an easy approach (SFINAE is another one):

template <typename> struct Tag{};

template<typename T, size_t N>
class Container
{
private:

    void quick_sort(tag<int>)
    {
        // ...
    }
    template <typename U>
    void quick_sort(tag<U>)
    {
        // ...
    }

public:
    void quick_sort()
    {
        quick_sort(Tag<T>());
    }
    // Some code ...
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302