使用clr和std :: thread

问题描述 投票:0回答:2

我正在为桌面创建一个UI抽象层。现在我正在实现.NET框架的功能。令人讨厌的是,如果我让用户在Visual Studio中创建CLR Windows窗体应用程序,他们就不能使用像std::thread这样的所有标准库,如果我让他们创建另一种类型的应用程序,控制台就会显示出来。

有没有办法将clr与std::thread一起使用,或者更好的是,有一种方法可以阻止控制台使用CLR控制台或CLR Empty项目启动(或将其隐藏在屏幕和任务栏中)。

谢谢

c++ .net stdthread
2个回答
0
投票

这是一个老问题,但万一有人遇到同样的问题:boost::thread是一个“负担得起”和实际的替代品(前提是你可以在项目中使用boost)。奇怪的是,它绕过了不兼容性。


0
投票

可能是一个老问题,但我之前研究过同样的问题。由于CLR不允许您在编译时包含std::thead,因此您可以尝试仅在链接时使用它。通常你可以解决这个问题,在你的标题中声明类,并将它们仅包含在你的cpp文件中。但是,您可以在头文件中转发声明自己的类,但不能用于名称空间std中的类。根据C ++ 11标准,17.6.4.2.1:

如果C ++程序向命名空间std或命名空间std中的命名空间添加声明或定义,则它是未定义的,除非另有说明。

此问题的解决方法是创建一个继承自std::thread的线程类,您可以转发声明。此类的头文件如下所示:

#pragma once
#include <thread>
namespace Threading
{
    class Thread : std::thread
    {
    public:
        template<class _Fn, class... _Args> Thread(_Fn fn, _Args... args) : std::thread(fn, std::forward<_Args>(args)...)
        {

        }
    private:

    };
}

在您想要使用线程的头文件中,您可以向前声明它,如:

#pragma once

// Forward declare the thread class 
namespace Threading { class Thread; }
class ExampleClass
{
    public:
        ExampleClass();
        void ThreadMethod();
    private:
        Threading::Thread * _thread;
};

在源文件中,您可以使用theading类,如:

#include "ExampleClass.h"
#include "Thread.h"

ExampleClass::ExampleClass() :
{
    _thread = new Threading::Thread(&ExampleClass::ThreadMethod, this);
}

void ExampleClass::ThreadMethod()
{
}

希望它可以帮助任何人。

© www.soinside.com 2019 - 2024. All rights reserved.