gpt4 book ai didi

c++ - 包装任意类型/非类型模板类的模板类

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:33 25 4
gpt4 key购买 nike

假设我有一个模板类 base和一类 wrapper其中包含 base 的实例化成员.我想定义类 wrapper这样它就依赖于模板参数包,它只是“传递”给 base 的实例化成员.

例如,考虑以下代码,它工作正常。

#include <iostream>

template <int i, int j>
struct base {
base()
{
std::cout << "i is " << i;
std::cout << " j is " << j << std::endl;
}
};

template <int... T>
struct wrapper {
base<T...> a;
};

int main()
{
wrapper<2, 3> x;
return 0;
}

预先知道base的所有模板参数是int , 我用 template <int...T>wrapper 的声明中.这允许有限的灵 active ,例如我可以为 base 的模板参数定义一些默认值。 , 不修改 wrapper .

但是,如果 base取决于类型和非类型模板参数的任意列表,我如何传递 wrapper 的模板参数至 base

例如,如果我知道 base 的所有模板参数可以隐式转换为 int(没有损失!),我可以定义 wrapper如以下程序

#include <iostream>

template <int i, bool j>
struct base {
base()
{
std::cout << "i is " << i;
std::cout << " j is " << (j ? "true" : "false") << std::endl;
}
};

template <int... T>
struct wrapper {
base<T...> a;
};

int main()
{
wrapper<2, true> x;
return 0;
}

但是如果 base像下面的程序一样同时依赖于类型和非类型模板参数,显然不可能简单地传递 wrapper 的模板参数。至 base :

#include <iostream>

template <class U, int i, int j>
struct base {
base()
{
std::cout << "i is " << i;
std::cout << " j is " << j << std::endl;
}
};

template <class... T>
struct wrapper {
base<T...> a;
};

int main()
{
wrapper<int, 2, 3> x; // Error!
return 0;
}

此程序无法编译,因为编译器需要 wrapper 的类型.

有没有办法写一个类wrapper将其模板参数“传递”给 base 类型的成员, 无论它们是什么

想法是为 wrapper 设置一个通用代码如果模板签名为 base,则无需修改变化。

最佳答案

您的问题有解决方案。它不是很优雅,需要特定的方法,但适用于您想要的情况:

template <class U, class i, class j>
struct base {
base()
{
std::cout << "i is " << i::value;
std::cout << " j is " << j::value << std::endl;
}
};

template <class ...T>
struct wrapper {
base<T...> a;
};

int main()
{
wrapper<int, std::integral_constant<int, 2>, std::integral_constant<int, 3>> x; //no error now!
return 0;
}

对于 C++17,它可以不那么冗长:

template<auto val>
using value_wrapper = std::integral_constant<decltype(val), val>;

int main()
{
wrapper<int, value_wrapper<2>, value_wrapper<3>> x; //no error now!
return 0;
}

关于c++ - 包装任意类型/非类型模板类的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51056414/

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