gpt4 book ai didi

c++ - 处理 2+ 模板参数的最佳方法?

转载 作者:太空狗 更新时间:2023-10-29 20:10:06 26 4
gpt4 key购买 nike

假设我有一个以下形式的模板化函数:

template<bool a, bool b, bool c>
void foo(){
if(a) printf("I do something when a is true!\n");
if(b) printf("I do something when b is true!\n");
if(c) printf("I do something when c is true!\n");
}

现在我有了这个函数,它可以在编译时专用于 8 种可能情况(a = b = c = true、a=b=true、c=false 等)。

我想用在运行时获得的 a、b 和 c 的值来调用这个函数。

如果模板只有一个参数,我可以这样做:

void caller(bool a){
if(a) foo<true>();
else foo<false>();
}

但是如果你有 2+ 个参数怎么办?你不能只做:

void caller(bool a, bool b, bool c){
foo<a,b,c>();
}

如果你用 if-else/switch 来做的话,那么疯狂的推理是不可取的。我想让编译器编译 foo 的 8 个版本,然后调用

foo<a,b,c>()

如果我有以下 bool 值,则可以做出等效的情况:

template<int a>
void foo(){
printf("%d", a);
}

假设我知道 a 可以在 0 和 32 之间变化。我想做类似的事情:

void caller(int a){
if(a<=32 && a>0) foo<a>();
else printf("ERROR!/n");
}

处理此类情况的最佳方法是什么?

最佳答案

But what if you have 2+ parameters? You cannot just do:

您可以使用可变参数模板、递归、高阶函数和std::integral_constant :

template <typename TF>
auto with_bool_constant(TF xf)
{
return xf();
};

template <typename TF, typename T, typename... Ts>
auto with_bool_constant(TF xf, T x, Ts... xs)
{
if(x)
return with_bool_constant([&](auto... ys)
{ xf(std::integral_constant<bool, true>{}, ys...); },
xs...);
else
return with_bool_constant([&](auto... ys)
{ xf(std::integral_constant<bool, false>{}, ys...); },
xs...);
};

用法:

template <bool a, bool b, bool c>
void f()
{
std::cout << std::boolalpha << a << " " << b << " " << c << "\n";
}

int main()
{
auto f_wrapper = [](auto a, auto b, auto c)
{
return f<a, b, c>();
};

with_bool_constant(f_wrapper, true, false, true);
}

wandbox example


Say that I know that a can vary between 0 and, i.e, 32. I would like to do something like:

您可以使用 boost::hana::make_range生成 0...32编译时范围(边界必须在编译时已知)。然后您可以使用 boost::hana::for_each或类似的编译时迭代构造,将运行时值转换为 std::integral_constant<int, X>并将类似的技术应用于我上面发布的技术。

关于c++ - 处理 2+ 模板参数的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984938/

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