Khayrullo Rustamov
Khayrullo Rustamov

Reputation: 21

Partial specializations for pointers and functions

These are template snippets for a method less which takes as input two generic arguments and returns bool result

How to implement partial specialization for functions?

template<typename T> //general form
class C{
    public: bool isLess(const T& v1, const T& v2){
        return v1<v2;
    }
};

template<> //explicit specialization for char*
class C<const char*>{
public: bool isLess(const char* v1, const char* v2){
    return strcmp(v1,v2) < 0;}
};

template <typename T> //partial specialization for pointers
class C<T*> {
public: bool isLess(T* v1, T* v2){return *v1 < *v2;}
};
//partial specialization for functions?

Upvotes: 0

Views: 117

Answers (3)

Nir Friedman
Nir Friedman

Reputation: 17704

You don't need to partially specialize function templates, because unlike with class templates you can have multiple functions with the same number, i.e. overloading.

#include <iostream>
#include <cstring>

template <class T> bool isLess(const T &v1, const T &v2) {
  std::cerr << "general\n";
  return v1 < v2;
}

bool isLess(const char *v1, const char *v2) {
  std::cerr << "str\n";
  return strcmp(v1, v2) < 0;
}

template <typename T> bool isLess(T *v1, T *v2) {
  std::cerr << "pointer\n";

  return *v1 < *v2;
}

int main() {
  int x = 0;
  int y = 1;
  auto s1 = "hey";
  auto s2 = "there";
  std::cerr << isLess(x, y) << "\n";
  std::cerr << isLess(s1, s2) << "\n";
  std::cerr << isLess(&x, &y) << "\n";
}

Output:

general
1
str
1
pointer
1

Upvotes: 0

krzaq
krzaq

Reputation: 16421

I think you want something more or less like the following:

template <typename R, typename... Args>
class C<R(*)(Args...)> {
    using func_ptr = R(*)(Args...);
    public: bool isLess(func_ptr l, func_ptr r) { return std::less<>{}(l, r); }
};

Upvotes: 2

lorro
lorro

Reputation: 10880

You don't have partial specialization for functions; what you have instead is overloads and std::enable_if<c, T>. Hint: you can have std::enable_if<c, T>::type for a function that returns T given c holds.

Upvotes: 1

Related Questions