我一直在学习模板和模板的专门化。我希望能够在一起添加两个模板参数。我可以用基本类型来完成这个任务,但是可以通过使用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'根据我有限的疯子经验,我认为这门课是可能的,但我找不到关于这个特定主题的多少信息。我相信答案在错误信息中。
发布于 2022-01-02 04:39:29
这将像预期的那样编译和工作。添加类型或函数。
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;
}https://stackoverflow.com/questions/70544576
复制相似问题