Search code examples
c++templatestemplate-templatesvariable-templates

Why is there no variable template template parameter?


I'm planning to create a variable template that takes (variable) template-template parameter and one typename:

template <template <typename> auto MetaPredicate, typename T>
constexpr bool has_predicate_v_ = requires {
  { MetaPredicate<T> } -> std::convertible_to<bool>;
}

Where the expectations are:

template <typename T>
struct dummy_01 {
    inline static constexpr bool value = true;
};

template <typename T>
inline constexpr bool dummy_01_v = dummy_01<T>::value;

std::cout << std::boolalpha << has_predicate_v_<dummy_01_v, int> << '\n'; // true

But that doesn't work. It would be useful if they exist in standard.

Another case is to create a metafunction count_if:

template <typename Type, template <typename> bool Predicate>
struct count_if {
    inline static constexpr size_t value = /** ... **/;
};

template <typename Type, template <typename> bool Predicate>
inline constexpr size_t count_if_v = count_if<Type, Predicate>::value;

// ...
count_if_v<std::tuple<int, double, void, size_t, unsigned short>, 
           std::is_integral_v> // yields to 3

There is also a proposal relating to my question: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2008r0.html

  • Why are there currently no variable template-template parameters/arguments?
  • What is the status of the proposal?
  • Are there any possible alternatives for variable template-template parameters/arguments?

Solution

  • You already linked to the proposal, so you’ve largely answered the question yourself. You might not know about the paper tracker that can answer the “status” question; it says that more motivating examples are sought (which might very well have been delayed by the pandemic), so maybe you should contribute yours!

    As for alternatives, the usual one is to key on the trait rather than the helper variable template. Obviously new code might have to wrap a (foundational) variable template with a helper trait class template to take advantage of this, but it works.