【发布时间】: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不满足的限制/要求
标签: c++ templates template-specialization std-function