gpt4 book ai didi

c++ - C++ 中是否可以有一个 "generic"模板参数,它可以是非类型模板参数,也可以是类型?

转载 作者:行者123 更新时间:2023-12-03 02:54:51 26 4
gpt4 key购买 nike

在 C++ 中,可以使用类型作为模板参数,例如:

template <typename T>
void MyFn();

在某些情况下也可以使用非类型作为模板参数,例如:

template <int64_t T>
void MyFn2();

我的问题是是否可以有一个可以同时是两者的“通用”模板参数?喜欢:

template <TypenameOrint64_t T>
void MyFn3();

这样 MyFn3<42>MyFn3<double>可以接受。

我如何使用它的一个例子:

template <typename ValType, ValType Head, ValType ...Tail>
struct ListS{

template <typename OutType, template <ValType ArgType> class Fn>
using MapHead = ListS<OutType, Fn<Head>::val, Tail...>;
};

template<int64_t N>
struct SquareS{
static constexpr const int64_t val = N * N;
};

using Sqrd = ListS<int64_t, 3, 4>::MapHead<int64_t, SquareS>;

static_assert(std::is_same<Sqrd, ListS<int64_t, 9, 4>>::value, "Values don't match");

上面是编译时值列表及其上的单个编译时“函数”的非常粗略的草图。是否可以使类似的东西也支持类型列表,而不仅仅是非类型模板参数兼容值的列表,而无需复制所有代码?

最佳答案

Is it possible to have a “generic” template parameter in C++, that can be either a non-type template parameter or a type?

简短回答:不。

长答案。

没有。我能想到的最好的混合类型和值是将值包装在类型中,例如使用 std::integral_constant 。

因此,您想要的代码几乎可以编写(C++17)如下

#include <utility>

template <typename ...>
struct ListS;

template <typename ValType, ValType Head, ValType ...Tail>
struct ListS<std::integral_constant<ValType, Head>,
std::integral_constant<ValType, Tail>...>
{
template <template <auto> class Fn, typename OutType = ValType>
using MapHead = ListS<std::integral_constant<OutType, Fn<Head>::value>,
std::integral_constant<OutType, Tail>...>;
};

template <auto N>
struct SquareS : public std::integral_constant<decltype(N), N*N>
{ };

int main ()
{
using T1 = ListS<std::integral_constant<long long, 3ll>,
std::integral_constant<long long, 4ll>>;
using T2 = T1::MapHead<SquareS>;
using T3 = ListS<std::integral_constant<long long, 9ll>,
std::integral_constant<long long, 4ll>>;

static_assert( std::is_same_v<T2, T3> );
}

在 C++17 之前,您不能使用 auto 作为模板值的类型,因此您应该进行一些简单的更正。

关于c++ - C++ 中是否可以有一个 "generic"模板参数,它可以是非类型模板参数,也可以是类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60016682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com