直接从指针转换为模板函数? [英] Directly casting from pointer to a template function?
问题描述
我试图获取一个指向函数模板实例的指针,并将其强制转换为void *:
I am trying to take a pointer to an instance of function template and cast it to void*:
#include <stdio.h>
void plainFunction(int *param) {}
template <typename T>
void templateFunction(T *param) {}
int main() {
void *addr1=&plainFunction; //OK
void *addr2=&templateFunction<int>; //Compile error
}
我收到以下错误(在Visual Studio 2008中)
I get the following error (in Visual Studio 2008)
main.cu(10) : error C2440: 'initializing' : cannot convert from 'void (__cdecl *)(T *)' to 'void *'
Context does not allow for disambiguation of overloaded function
为什么会这样?函数 templateFunction
(对于具体类型 T = int
)没有重载.可以推断出我要引用的函数实例.
Why is it happening? Function templateFunction
(for concrete type T=int
) is not overloaded. It is possible to deduct which instance of the function I am refering to.
如果我将错误的行替换为:
If I replace the erroneus line with:
void (*foo)(int*)=&templateFunction<int>;
void *addr2=foo;
它编译没有问题.
谢谢!
更新:
如詹姆士(谢谢你)所建议的那样,当普通指针 void *
被伪函数指针 void(*)()
代替时,它使错误消失了:
When normal pointer void*
is replaced by dummy function pointer void(*)()
, as suggested by James (thank you), it makes the error go away:
void (*addr1)()=(void(*)())&plainFunction;
void (*addr2)()=(void(*)())(&templateFunction<int>);
但是,如果错误是由于将函数指针转换为普通指针而引起的,则在两种情况下编译器都应进行投诉.但是,事实并非如此,因此我继续假设它至少对于此编译器是正确的.如果我没记错的话,该标准只是说函数指针不必像普通指针那样被表示,但这并不禁止.
However, if the error was caused by casting a function-pointer to a normal pointer, the compiler should complain in both cases. It does not however, so I continue to assume that it is correct at least for this compiler. If I am not mistaken, the standard just says that function pointers don't have to be represented like normal pointers, but it does not forbid that.
推荐答案
从技术上来讲都是错误的:在C ++中,您不能将函数指针转换为 void *
.
Both are technically wrong: in C++, you can't convert a function pointer to a void*
.
指向函数的类型(如 void(*)(int *)
)与指向对象的类型(如 void *
此处).
Pointer-to-function types (like void (*)(int*)
here) are a completely different class of types than pointer-to-object types (like void*
here).
完全允许转换的Visual C ++(例如,在 void * addr1 =& plainFunction;
中)是一种语言扩展(使用/Za
标志进行编译,会禁用语言扩展,导致两条线都被拒绝.
Visual C++ allowing the conversion at all (e.g. in void* addr1 = &plainFunction;
) is a language extension (compiling with the /Za
flag, which disables language extensions, causes both lines to be rejected).
可以肯定,该错误有点令人误解,尽管其他一些编译器同样无济于事(Comeau报告错误:没有函数模板"templateFunction"的实例与所需类型相匹配").
The error is a bit misleading, for sure, though some other compilers are equally unhelpful (Comeau reports "error: no instance of function template "templateFunction" matches the required type").
这篇关于直接从指针转换为模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!