为 vardiac 和普通模板设置类型名称默认值
setting typename default value for vardiac and normal template
template<typename T, T... Xs> class Nzm
{
private:
template<typename... Ts> static constexpr T Max(Ts... xs);
template<typename Tx> static constexpr T Max(Tx x)
{
return x;
}
template<typename T1, typename T2, typename... Ts> static constexpr T Max(T1 x, T2 y, Ts... xs)
{
return y > x ? Max<T2, Ts...>(y, xs...) : Max<T1, Ts...>(x, xs...);
}
public:
static const T Z = Max(Xs...);
};
int main() {
static_assert(Nzm<int,1,2,3,4,5,6>::Z==5,"XYZ");
return 0;
}
我已经知道所有的字体名都是int,我只想使用
Nzm<1,2,3,4,5,6>
而不是
Nzm<int,1,2,3,4,5,6>
这是用于编译时执行,没有代码或提示使其运行时。这可能吗?将所有这些类型名设置为 int ?
快速的解决方案是使用 using
声明来获取 int。
template<int... x>
using helper = Nzm<int, x...>;
int main() {
static_assert(helper<1, 2, 3, 4, 5, 6>::Z == 6, "XYZ");
return 0;
}
另一种(更好的)方法是修改 Nzm 并将所有typename
模板替换为int
模板。参数和模板参数之间存在冗余,因此您可以摆脱参数。
template<int... Xs> class Nzm
{
private:
template<int x> static constexpr int Max()
{
return x;
}
template<int x, int y, int... rest> static constexpr int Max()
{
return x > y ? Max<x, rest...>() : Max<y, rest...>();
}
public:
static const int Z = Max<Xs...>();
};
int main() {
static_assert(Nzm<1, 2, 3, 4, 5, 6>::Z == 6, "XYZ");
return 0;
}
如果你想要一个接受int
参数包的模板,请给自己一个这样的模板:
template<int ...Is> class Nzm {
// Your implementation follows
};
模板可以接受非类型的参数(其中包括整数参数),因此它们可以接受类似的参数包。
相关文章:
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- 变量始终在函数中重置为默认值
- 如果输入类型与目标类型不同,"cin"变量是否重置为某个默认值?
- 具有默认类型和值的模板参数
- 可变类类型的丢弃值表达式的行为与可变内置类型的丢弃值表达式的行为不同
- 具有默认值的参数的自动类型扣除
- 根据模板参数的默认值启用模板参数类型的自动扣除
- 为 vardiac 和普通模板设置类型名称默认值
- 调用类型的标记构造函数(如果可用),否则为默认值
- 未知模板类型的默认值或零值
- 内置类型的返回const值
- 基本类型的std ::向量的默认值
- AnsiString作为Embarcadero C++Builder中字符串类型的默认值
- 如何获取任何类型的默认值
- 为LONGLONG类型指定默认值.明戈GCC
- 如果我在 C++ 中为 "std::string &" 类型的参数指定默认值,这会导致内存泄漏吗?
- 为什么我的对象中的变量被重置为默认值
- 如何将未知类型的数据成员初始化为默认值
- 内置类型的C++默认初始化
- 内置类型的模板参数默认值