我正在尝试创建一个标识函数的类模板,我可以在其中识别函数何时专门用于类模型R (*) (),但是std::function你可以声明 return_type (),并且std::is_same< int(), int (*) () >.::value为零.
这是什么int ()说法意味着与之间有什么区别int ()和?
int (*) ()
int ()函数声明或函数类型int (*)()也是函数类型的指针.但是它是类型函数吗?它是类似的东西,或者像是什么?我怎样才能使这个程序输出1? int (std::string::)() int std::string::()std::function int(const std::string&)
#include <iostream>
template<typename A,typename B>
struct IsSame{
enum{
value = 0};
};
template<typename A>
struct IsSame<A,A>{
enum{
value = 1
};
};
typedef int (SumType)(int,int)const;
class X{
public:
SumType sum;
};
int X::sum(int a,int b)const{
return a+b;
}
int main()
{
std::cout << IsSame< int (const std::string&,int,int)const,
decltype( &X::sum)>::value;
}
Run Code Online (Sandbox Code Playgroud)
R (*) ()一个函数有一个类似的类型void(),如果你取一个地址,你会得到一个指向该函数的指针void(*)().它们的类型不同,尽管函数可以衰减为指向函数的指针,其方式类似于数组衰减为指向第一个成员的指针.
这意味着您可以声明一个函数:
void f();
Run Code Online (Sandbox Code Playgroud)
并将其分配给指向函数的指针(具有相同的签名):
void (*p_to_f)() = f;
Run Code Online (Sandbox Code Playgroud)
并且函数衰减到指向函数的指针.
这就是为什么我认为这可能是很难理解的区别void()和void(*)(),但他们是不同的类型,而这种差距可以在模板中是重要的(如果这种衰退不一定会发生).
当没有发生衰减时,一个重要的例子是匹配模板特化.考虑一下std::function例如:
template <class>
class function;
template <class R, class ... Args>
class function<R(Args...)> { /* ... stuff ... */ };
Run Code Online (Sandbox Code Playgroud)
专门化在函数类型上的事实与专门用于指向函数类型的事实不同.
function<void(int,int)> f;//matches specialisation
function<void(*)(int,int)> g;//does not match specialisation
Run Code Online (Sandbox Code Playgroud)
响应OP的注释(现已删除):
为了匹配指向函数的指针,您可以执行以下操作:
template <class R, class ... Args>
function<R(*)(Args...)> : function<R(Args...>{};
Run Code Online (Sandbox Code Playgroud)
这实际上意味着你将函数和指针视为相同的函数.如果要匹配尽可能多的函数,还必须考虑成员函数,const成员函数和noexcept函数(从C++ 17开始).如果你想完全彻底的,还有还有&,&&,const &,const&&,volatile,等...但我不会担心这些,除非他们真的上来了.
| 归档时间: |
|
| 查看次数: |
206 次 |
| 最近记录: |