decltype 的错误参数 [英] Incorrect argument to decltype
问题描述
两天前我问过关于创建线程以使用 Win32 API 运行非静态类方法的问题,我几乎得到了解决方案,但有一些让我感到困惑的东西,所以我在发布之前的答案之前问了这个问题问题.
I asked two days ago about creating threads to run non-static class methods with the Win32 API, and I almost got a solution but there is something confusing me, so I'm asking this question before posting the answer in my previous question.
我正在尝试使用此代码来线程化返回类型未知的函数:
I'm trying to use this code to thread a function with an unknown return type:
template <class R, R func() >
unsigned int usualfunc() {
func();
return 1;
}
template <class R>
int Start(R(*func)()) {
typedef decltype(&usualfunc<int, func>) D; // I get the error here , I can't get the address of the template function directly I need this
D p = &usualfunc<R, func>;
uintptr_t add = (uintptr_t)p;
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)add, 0, 0, 0);
func();
return 1;
}
int main() {
Start(ltest);
}
当我尝试编译上面的代码时,我得到:
When I try to compile the above code, I get :
错误 3556 'usualfunc':'decltype' 的参数不正确
error 3556 'usualfunc': incorrect argument to 'decltype'
MSDN 上描述了错误描述:
The error description is described on MSDN:
然而,我在此之前尝试了另一个代码,它工作得很好,但我对语法不是很好:
However, I tried another code before this, and it works just fine, but I wasn't very good with the syntax:
template <class R, R func() >
unsigned int usualfunc() {
func();
return 1;
}
template <class R,R func()>
int Start() {
typedef decltype(&usualfunc<int, func>) D; // works well
D p = &usualfunc<R, func>;
uintptr_t add = (uintptr_t)p;
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)add, 0, 0, 0);
func();
return 1;
}
int main() {
Start<int,ltest>(); // works
}
我知道这段代码已经足够了,但我想使用 Start(ltest)
而不是 Start
.
I know this code is enough, but I'd like to use Start(ltest)
instead of Start<int,ltest>()
.
注意:没有人说我应该在usualfunction
中使用函数作为参数,我使用它作为模板参数,因为CreateThread()
不能通过一个函数作为参数.
Note: no one say that I should use the function as parameter in usualfunction
, I'm using it as a template parameter because CreateThread()
can't pass a function as a parameter.
推荐答案
模板参数必须在编译时已知.但是,您尝试使用普通函数参数 func
作为模板参数.
Template parameters must be known at compile-time. However you attempt to use the normal function parameter func
as a template argument.
在第二个代码中,您提供了一个模板参数作为模板参数,这很好.
In the second code you give a template parameter as the template argument, which is fine.
由于与此代码类似的原因,您的第一个代码是错误的:
Your first code is wrong for a similar reason as this code:
template<int X> void f() { }
int main(int argc, char **argv) { f<argc>(); }
虽然错误信息有点模糊.
although the error message is a bit more obscure.
从 C++17 开始,您可以通过对第二个代码进行此修改来获得所需的语法:
Since C++17 you can get the syntax you want by making this modification to your second code:
template <auto func>
int Start() {
using R = decltype(func());
// proceed as before...
并将其称为Start
.
在 C++17 之前,您可以在第二个代码中使用宏:
Prior to C++17 you could use a macro with your second code:
#define START(func) Start<decltype(func()), func>
这篇关于decltype 的错误参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!