我有一个编译时情况可以通过使用宏来解决,但我想知道是否有更好的路线。这是用于说明目的的概念的非常简化的版本(真实的东西有很多“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/