类型和函数的模板类特化添加

Posted

技术标签:

【中文标题】类型和函数的模板类特化添加【英文标题】: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'

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

【问题讨论】:

Non-type_template_parameter 有一些 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;

【讨论】:

以上是关于类型和函数的模板类特化添加的主要内容,如果未能解决你的问题,请参考以下文章

C++模板进阶(非类型模板参数类模板的特化和模板的分离编译)

C++模板详解:泛型编程模板原理非类型模板参数模板特化分离编译

C++模板详解:泛型编程模板原理非类型模板参数模板特化分离编译

C++模板(函数模板/类模板)

C++模板(函数模板/类模板)

C++模板进阶操作 —— 非类型模板参数模板的特化以及模板的分离编译