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

标签 c++ templates c++17 template-argument-deduction

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

相关文章:

c++ - Boost力定向布局问题

c++ - 使用 typeid 分离代码执行

c++ - 如何将一个 std::vector move 附加到另一个?

c++ - 结构化绑定(bind)和基于范围的;在 gcc 中抑制未使用的警告

c++ - 如何实例化从抽象类派生的类

c++ - OpenCV undistortPoints 和 triangulatePoint 给出奇怪的结果(立体声)

c++ - 可读 Node 流到 native c++ 插件 InputStream

c++ - '仅将成员函数添加到类的专用模板

c++ - 为什么这个模板函数调用在这个函数内部不起作用?

c++ - 使用动态矩阵进行特征分解时出现错误