gpt4 book ai didi

C++模板化模板推导回避可能吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:53:38 25 4
gpt4 key购买 nike

我有一个可以通过使用宏来解决的编译时情况,但我想知道是否有更好的方法。这是一个非常简化的概念版本,用于说明目的(真实的东西有更多的“Do”状态并在宏中使用开关):

int DoA(int a, int b)
{
return a + b;
}

int DoB(int a, int b)
{
return a - b;
}

template <typename F> int DoFunc1(int a, int b, F func)
{
return func(a,b);
}

template <typename F> int DoFunc2 (int a, int b, F func)
{
a *= 2;
b++;
return func(a,b);
}

#define ChooseFunc(type, a, b, func) (((type)) ? (func)((a), (b), (DoA)) : (func)((a), (b), (DoB)))

int CallerA(bool state, int a, int b)
{
return ChooseFunc(state, a, b, DoFunc1);
}

int CallerB(bool state, int a, int b)
{
return ChooseFunc(state, a, b, DoFunc2);
}

现在我想做的就是放弃宏,改用这样的东西:

int ChooseFunc(bool type, int a, int b, auto func)
{
if (type)
return func(a, b, DoA);

return func(a, b, DoB);
}

但显然这不会编译,因为编译器无法推断模板类型。

问题是,有没有更好的巧妙方法来做到这一点?

最佳答案

写一个仿函数类

struct Func1 {
template<typename F>
int operator()(int a, int b, F func) { return DoFunc1(a, b, func); }
};

// Likewise for DoFunc2

并改为传递一个仿函数。

关于C++模板化模板推导回避可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48069719/

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