将函数类型作为模板参数传递不会编译

Passing Function Type As Template Parameter Does Not Compile

本文关键字:参数传递 编译 函数 类型      更新时间:2023-10-16

所以我有一个类,它接受两个模板参数,一个是类型,一个是所用函数的类型,它有一个reduce函数将这个函数重复应用于数组。但是,我收到编译错误。

function_template_test.cpp: In instantiation of 'class _C<int, int(int, int)>':
function_template_test.cpp:36:33:   required from here
function_template_test.cpp:11:17: error: field '_C<int, int(int, int)>::op' invalidly declared function type
BinaryOperator op;

这是我的代码。我在 main 方法下面有一个类和驱动程序代码。

#include<iostream>
template<typename _T>
_T addition(_T x,_T y)
{
return x+y;
}
template<typename _T,typename BinaryOperator>
class _C
{
private:
BinaryOperator op;
public:
_C(BinaryOperator op)
{
this->op=op;
}
_T reduce(_T*begin,_T*end)
{
_T _t_=*begin;
++begin;
while(begin!=end)
{
_t_=this->op(_t_,*begin);
++begin;
}
return _t_;
}
_T operator()(_T*begin,_T*end)
{
return this->reduce(begin,end);
}
};
int main(int argl,char**argv)
{
int arr[]={1,4,5,2,9,3,6,8,7};
_C<int,decltype(addition<int>)>_c_=_C<int,decltype(addition<int>)>(addition<int>);
std::cout<<_c_(arr,arr+9)<<std::endl;
return 0;
}

您指定函数类型作为BinaryOperator的模板参数,该参数不能用作op类型的数据成员;您可以改为指定函数指针类型

_C<int,decltype(addition<int>)*>_c_=_C<int,decltype(addition<int>)*>(addition<int>);
//                            ^                                   ^

BTW:以下划线开头的_C名称保留在C++中。

通常,当将函数分配给函数指针时,您不需要明确添加运算符(&(的地址,因为将函数本身分配给变量是无效的,因此语言会自动为您添加它。但是,在函数名称上执行decltype时,您确实会得到函数类型而不是函数指针。例如,尝试编译以下内容,所有static_assert都应该通过:

#include <type_traits>
void foo() {}
int main()
{
auto a = foo;
auto b = &foo;
static_assert(std::is_same_v<decltype(a), decltype(b)>,"a and b are function pointers");
static_assert(!std::is_same_v<decltype(a), decltype(foo)>,"foo is not a function pointer");    
static_assert(std::is_same_v<decltype(a), decltype(&foo)>,"&foo is a function pointer");    
}

您的代码本质上等效于:

#include <type_traits>
void foo() {}
int main()
{
decltype(foo) c = foo;
}

这不编译。将其更改为此可解决此问题:

#include <type_traits>
void foo() {}
int main()
{
decltype(&foo) c = foo;
}

对代码的修复是将其更改为:

_C<int,decltype(&addition<int>)>_c_=_C<int,decltype(&addition<int>)>(addition<int>);

或者,您可以通过直接构造来避免重复类型:

_C<int,decltype(&addition<int>)>_c_(addition<int>);

或使用auto

auto _c_=_C<int,decltype(&addition<int>)>(addition<int>);