【问题标题】:Template Class Specialization Addition of Types and Functions类型和函数的模板类特化添加
【发布时间】:2021-12-31 17:51:47
【问题描述】:

我一直在学习模板和模板专业。我希望能够将两个模板参数一起添加。我可以用基本类型来做到这一点,但也可以用函数来做到这一点,以及使用 lambda 函数和类专业化。

以下代码无法编译:

template<class R>
class Adder
{
public:
    template<R A, R B>
    static R Add() { return A + B; }
protected:
};

template<class R, class ...Args>
class Adder<std::function<R(Args...)>>
{
public:
    template<std::function<R(Args...)> A, std::function<R(Args...)> B>
    static std::function<R(Args...)> Add()
    {
        std::function<R(Args...)> Func = [](Args...) -> R { return A(Args...) + B(Args...); };
        return Func;
    }
protected:
};


double Test1(double x)
{
    return x;
}

int main()
{

    int a = Adder<int>::Add<2,2>();

    std::function<double(double)> Func = Adder<std::function<double(double)>>::Add<Test1, Test1>();

    return 0;
}

我收到以下错误:

error C2993: 'std::function<double (double)>': is not a valid type for non-type template parameter 'A'
message : 'function<double __cdecl(double)>' is not a literal class type
message : see reference to class template instantiation 'Adder<std::function<double (double)>>' being compiled
error C2993: 'std::function<double (double)>': is not a valid type for non-type template parameter 'B'
message : 'function<double __cdecl(double)>' is not a literal class type
error C2672: 'Adder<std::function<double (double)>>::Add': no matching overloaded function found
error C2993: 'std::function<double (double)>': is not a valid type for non-type template parameter 'A'
error C2993: 'std::function<double (double)>': is not a valid type for non-type template parameter 'B'

根据我有限的疯子经验,我认为这门课是可能的,但我无法找到关于这个特定主题的太多信息。我确定答案在错误消息中。

【问题讨论】:

标签: c++ templates template-specialization std-function


【解决方案1】:

这将按预期编译和工作...添加类型或函数。

template<class R>
class Adder
{
public:
    template<R A, R B>
    static R Add() { return A + B; }
protected:
};

template<class R, class ...Args>
class Adder<std::function<R(Args...)>>
{
public:
    template<R Func1(Args...), R Func2(Args...)>
    static std::function<R(Args...)> Add()
    {
        return [](Args... Vars) -> R { return Func1(Vars...) + Func2(Vars...); };
    }
protected:
};

int Test1(int x)
{
    return x;
}

int main()
{
    int a1 = Adder<int>::Add<1, 1>();
    std::function<int(int)> F1 = Adder<std::function<int(int)>>::Add<Test1, Test1>();
    int V1 = F1(1);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多