using clr and std::thread

前端 未结 2 1206
灰色年华
灰色年华 2021-01-27 08:42

I\'m creating an UI abstraction layer for desktops. Now I\'m implementing the functionality of the .NET framework. The annoying thing is that if I let the users create a CLR Win

相关标签:
2条回答
  • 2021-01-27 08:51

    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:

    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.

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

    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.

    0 讨论(0)
  • 2021-01-27 08:58

    This is an old question, but in case someone hits the same problem: boost::thread is an "affordable" and practical replacement (provided you can use boost in your project). Strangely, it bypasses the incompatibility.

    0 讨论(0)
提交回复
热议问题