Gleb Belov
Gleb Belov

Reputation: 1

C++ template function overload resolution: generic vs specialized template parameters

The below example runs as I expect in Clang and G++ (C++17), but fails when used analogously in a larger project (again in both compilers).

#include <array>
#include <iostream>
#include <functional>

/// General template
template <class Item>
inline void VisitArguments(const Item& item, std::function<void(int)> f) {
  f(5);
  std::cout << "General." << std::endl;
}

/// Specialized template.
/// It is used in this small program,
/// but is not 'discovered' by the compiler when part of a larger project
/// and needs to appear before the first template.
template <size_t N>
inline void VisitArguments(const std::array<int, N>& cnt, std::function<void(int)> f) {
  f(6);
  std::cout << "More specialised." << std::endl;
}

int main() {
  std::array<int, 3> arr;
  int d{};
  std::function<void(int)> f = [&d](int v) { d=v; };
  VisitArguments(arr, f);
  return 0;
}

When the two template functions are part of a larger project, the compilers do not see the 2nd template. For it to be used, it needs to appear before the current 1st template.

Thus, the resolution order seems random. Is this correct, or should the more specialized template be always preferred?

Upvotes: 0

Views: 9

Answers (0)

Related Questions