将函数类型作为模板参数传递不会编译
Passing Function Type As Template Parameter Does Not Compile
所以我有一个类,它接受两个模板参数,一个是类型,一个是所用函数的类型,它有一个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>);
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用 SFINAE 作为模板参数的编译时递归
- 使用引用与指针将数组作为参数传递
- 将函数类型作为模板参数传递不会编译
- 将类中声明的函数作为参数传递会导致编译错误
- 引用将参数传递给函数时出现奇怪的编译错误
- 编译错误:在类构造函数中将抽象类作为参数传递