且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用clr和std :: thread

更新时间:2023-11-11 22:43:34

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

Might be an old question, but I looked into this same problem before. Since CLR does not allow you to include std::thead at compile time, you could try to use it only at linking time. Normally you could resolve this be forward declaring the class in your header and including them only in your cpp files. However you can forward declare your own classes in header files, but you can't for classes in namespace std. According to the C++11 standard, 17.6.4.2.1:

如果C ++程序添加了声明或命名空间std或命名空间std中的命名空间的定义除非另有说明.

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.

此问题的一种解决方法是创建一个线程类,该线程类继承自可以向前声明的 std :: thread .该类的头文件如下所示:

A workaround for this problem is to create a threading class that inherits from std::thread that you can forward declare. The header file for this class would look like:

#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:

    };
}

在要使用该线程的头文件中,可以像下面这样向前声明它:

In the header file that you would like to use the thread you can do forward declare it like:

#pragma once

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

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

In your source file you can then use the theading class like:

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

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

void ExampleClass::ThreadMethod()
{
}

希望它可能对任何人都有帮助.

Hope it might help anyone.