3

In C++26, the following code is legal (see p2841r7 and Herb Sutter's article):

template<typename<typename> concept C, template<typename> auto vt, typename T>
requires C<T>
auto f(T v) {
    return vt<T> + v;
}

template<typename T>
constexpr auto type_size = sizeof(T);

int main() {
    f<std::integral, type_size>(8);
}

However, the following code is still illegal in C++26:

template<typename T>
T f1(T v) { return v + 1; }

template<typename T>
T f2(T v) { return v + 2; }

// There can be many similar template functions like f3, f4, ...

template<template<typename> Fn??? f, typename T>
T g(T v) { return f<T>(v); }

int main() {
    g<f1, int>(4);
    g<f2, int>(5);
    // g<f3, int>(6);
    // g<f4, int>(7);
    // ...
}

Now that concepts and variable templates are allowed to be the template parameter, why are function templates still not allowed likewise?

7
  • 2
    For your specific code, template<typename T, T (*f)(T)> T g(T v) { return f(v); } works. Remember to change the order or the template arguments when using g. Commented Jul 3, 2025 at 16:23
  • 1
    Then it seems unnecessay since we already have a nice solution to the problem. Commented Jul 3, 2025 at 16:26
  • 2
    Yes and that solution even works in C++11. @Someprogrammerdude I took the liberty of changing your example (C++11, let main return result so the result can be checked). godbolt.org/z/ar9qqnh7W Commented Jul 3, 2025 at 16:30
  • 1
    @PepijnKramer: only works if you provide T and even then, you have f2<int> but cannot access f2<float>. Commented Jul 3, 2025 at 16:37
  • 1
    Lambda can do the job though in C++20 Demo Commented Jul 3, 2025 at 16:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.