gpt4 book ai didi

c++ - decltype 的参数不正确

转载 作者:行者123 更新时间:2023-11-30 02:19:38 24 4
gpt4 key购买 nike

我两天前问过有关创建线程以使用 Win32 API 运行非静态类方法的问题,我几乎找到了解决方案,但有些事情让我感到困惑,所以我在发布答案之前问了这个问题问题。

我正在尝试使用此代码对具有未知返回类型的函数进行线程处理:

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);
}

当我尝试编译上面的代码时,我得到:

error 3556 'usualfunc': incorrect argument to 'decltype'

错误描述在MSDN上有描述:

Compiler Error C3556

然而,在此之前我尝试了另一个代码,它工作得很好,但我的语法不是很好:

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<int,ltest>() .

注意:没有人说我应该使用函数作为 usualfunction 中的参数,我将其用作模板参数,因为 CreateThread()不能将函数作为参数传递。

最佳答案

模板参数必须在编译时已知。但是您尝试使用正常的函数参数 func作为模板参数。

在第二个代码中,您提供了一个模板参数作为模板参数,这很好。

您的第一个代码错误的原因与此代码类似:

template<int X> void f() { }

int main(int argc, char **argv) { f<argc>(); }

虽然错误信息有点模糊。


从 C++17 开始,您可以通过对第二个代码进行以下修改来获得所需的语法:

template <auto func>
int Start() {
using R = decltype(func());
// proceed as before...

并将其命名为Start<ltest>(); .

在 C++17 之前,您可以在第二个代码中使用宏:

#define START(func) Start<decltype(func()), func>

关于c++ - decltype 的参数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com