C++11 Polyfills

坚强是说给别人听的谎言 提交于 2020-02-02 07:13:05

问题


I am starting a new project that will be targeting MSVC, GCC (latest), GCC 4.3 ARM and more. The waf build system we have built has C++11 feature detection of the compiler.

I now have preprocessor macros for all features in compiler that I am targeting for C++11, for example #ifdef WAF_FEATURE_CXX_STRONGLY_TYPED_ENUMS. I can therefore compile different code for what the compiler supports. As GCC nearly supports it all be MSVC isn't even close (even with MSVC 11)

This got me thinking about web development polyfills - if the feature isn't available implement it with the feature set available.

This is no way near as simple as web development polyfills as for C++11 but is there anything that I can simply implement with C++03 if the compiler doesn't support it?

This boils down to the fact that I want to use strongly typed enumerators in my public API but the scoping MyClass::MyEnumerator::EnumValue will look more like MyClass::EnumValue in C++03. Is there anyway I can get the same to occur in C++03 easily:

class MyClass {
    public:
#ifdef WAF_FEATURE_CXX_STRONGLY_TYPED_ENUMS
        enum class MyEnumerator : unsigned int {
#else
        enum MyEnumerator {
#endif
             EnumValue = 0
        }
    void method(MyEnumerator e);
}

MyClass mc = new MyClass();
mc.method(MyClass::MyEnumerator::EnumValue) // C++11
mc.method(MyClass::EnumValue)               // C++03 :(

回答1:


This is what you'll need to do (I made other trivial fixes about pointers and non-pointer access). Bsically, it's what @demi said. I had to make a dummy enum name. This works in g++-4.7.

class MyClass {
    public:
#if __cplusplus > 201000
        enum class MyEnumerator : unsigned int {
             EnumValue = 0
        };
    void method(MyEnumerator e) {}
#else
        class MyEnumerator {
        public:
          enum Dummy {
             EnumValue = 0
          };
        };
    void method(MyEnumerator::Dummy e) {}
#endif
};

int main() {
    MyClass mc;
    mc.method(MyClass::MyEnumerator::EnumValue); // C++11 or C++03
}



回答2:


You may emulate enum class as class. Your boilerplate code will be only in definition, but usage will be same for C++11 and C++03, and may be done with templates/macros. Look answer here



来源:https://stackoverflow.com/questions/10681833/c11-polyfills

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!