开发者

The explicit keyword in MS Visual Studio 4.1

I am implementing a smart pointer class using generics and I wanted to force users of this class to properly construct the smart pointer using syntax such as

 MyReference<TestCls>(mytest3))

or

MyReference<TestCls> mytest4(new TestCls());

so I have used the explicit keyword on the CTOR, to prevent this:

MyReference aRef = NULL;

However due to unfortunate circumstances beyond my control, I am working on code that is compiled using the ancient MSVC++ 4.1 compiler. I get the following errors when I include 开发者_StackOverflowthe explicit keyword:

MyReference.h(49) : error C2501: 'explicit' : missing decl-specifiers

MyReference.h(51) : error C2143: syntax error : missing ';' before ''

MyReference.h(52) : error C2238: unexpected token(s) preceding ':'

MyReference.h(52) : error C2059: syntax error : 'int constant'

When I add a #define explicit those errors disappear. This was a hack on my part, just to get the compiler to ignore the keyword. I'm guessing that this means that explicit is not supported by yon olde compiler. Can someone confirm this and is there anyone out there with knowledge of a workaround solution for this?

Merci Beaucoups, Dennis.


This site has a workaround for this, namely:

Unfortunately, older compilers may not support the use of "explicit", which could be a headache. If you're stuck working with an out-of-date compiler and can't get one that has better support for the C++ standard, your best solution may be to take advantage of the fact that only a single implicit conversion will take place for a given value. You can exploit this by using an intermediate class that implicitly creates an object of each type, and then have your main class implicitly create objects from that class:

class proxy
{
    public:
    proxy(int x) : x(x) {} ;
    getValue() { return x; }

    private:
    int x;

};

class String
{
    // this will be equivalent of explicit
    String(proxy x) { /* create a string using x.getValue(); */ }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜