C++模板模板非类型参数

C++ template template non-type parameter

我正在努力实现以下目标:

template<template<typename> bool Function_, typename ... Types_>
constexpr auto find(Tuple<Types_ ... >) noexcept
{
    // ... 
}

可能的功能可能是:

template<typename T>
inline constexpr bool is_pointer_v = is_pointer<T>::value;

那么 find 的用法是:

Tuple<int, char, void *> t;
find<is_pointer_v>(t);

不用担心find的实现,我只是问如何做“template < typename > bool Function_”,因为bool部分目前在c++中是无效的。

感谢任何帮助!

编辑:

这里是一个例子,说明为什么我不能将“is_pointer”传递给函数:

template<typename T_>
constexpr auto add_pointer(Type<T_>) noexcept
{ return type_c<T_ *>; }

template<typename F_, typename T_>
constexpr auto apply(F_ f, Type<T_> t) noexcept
{
    return f(t);
}

int main(void)
{
    Type<int> t_i;
    apply(add_pointer, t_i);
}

这会产生编译器错误:

error: no matching function for call to ‘apply(< unresolved overloaded function type >, sigma::meta::Type&)’ apply(add_pointer, t_i);

I am just asking about how to do "template < typename > bool Function_" as the bool part is invalid in c++ currently.

据我所知,模板-模板参数是完全不同的东西。它们适用于容器,而不是功能。所以 class,而不是 bool.

here is an example of why I can't pass the "is_pointer" to the function

你的例子不起作用,因为 add_pointer 是一个模板函数,所以当你调用

apply(add_pointer, t_i);

编译器不知道要使用 add_pointer 的哪个版本(哪种类型 T)。

解决办法可以显式一下,如下面简化的例子

#include <tuple>
#include <iostream>

template <typename T>
constexpr auto add_pointer(std::tuple<T>) noexcept
 { std::cout << "add_pointer" << std::endl; return 0; }

template <typename F, typename T>
constexpr auto apply(F f, std::tuple<T> t) noexcept
 { return f(t); }

int main(void)
 {
   std::tuple<int> t_i { 1 };

   apply<int(*)(std::tuple<int>)>(add_pointer, t_i);
 }

但我明白解释 int(*)(std::tuple<int>) 是一件很痛苦的事情。

你可以使用传递 t 的事实来简化一点,这样你就可以推断出函数接收到的参数的类型,但是(对于通用解决方案)我不知道如何避免明确函数的 return 类型(也许是可能的,但(此时)我不知道。

所以可以简化调用如下

apply<int>(add_pointer, t_i);

下面是一个更一般的例子

#include <tuple>
#include <iostream>

template <typename ... Ts>
constexpr auto add_pointer(std::tuple<Ts...> const &) noexcept
 { std::cout << "add_pointer" << std::endl; return 0; }

template <typename R, typename ... Ts, 
          typename F = R(*)(std::tuple<Ts...> const &)>
constexpr auto apply(F f, std::tuple<Ts...> t) noexcept
 { return f(t); }

int main(void)
 {
   std::tuple<int> t_i { 1 };

   apply<int>(add_pointer, t_i);
 }

any help is appreciated!

您可以简单地将您的函数包装在函子中。
作为一个最小的工作示例:

template<typename>
struct Type {};

template<typename>
struct type_c {};

template<typename T_>
struct add_pointer {
    static constexpr auto invoke(Type<T_>) noexcept
    { return type_c<T_ *>{}; }
};

template<template<typename> class F_, typename T_>
constexpr auto apply(Type<T_> t) noexcept {
    return F_<T_>::invoke(t);
}

int main(void) {
    Type<int> t_i;
    apply<add_pointer>(t_i);
}

如果您不能直接更改它们,请创建仿函数,通过静态 constexpr 成员方法将所有内容转发给正确的函数。