C++/CLI : Portable operators?

D

dchunt

I have a C++/CLI class I wish to have source compatible with regular
C++. I'm looking for a good way to handle the operators :

public value class SampleClass
{
//- C++/CLI
static bool operator==(SampleClass %, SampleClass %);

//- C++
//- friend bool operator==(const SampleClass &, const SampleClass
&);
//- bool operator==(const SampleClass &) const;

int value_; //- Just to have something
};

The types and the class declaration are easily handled by macros, but
the operators are a lot more hideous. I'd like the operator== in
C++/CLI to be in the class -- I want it reflected -- but static
operator== is just plain illegal in C++. The best I've got is :

//- Yuck.
#if defined(__cplusplus_cli)
#define VALUE_CLASS(name) public value struct name
#define OP_DECLARE(ret,name,p1,p2) \
static ret operator ## name(p1, p2)
#define OP_DEFINE(cls,ret,name,p1,p2) \
ret cls::blush:perator ## name(p1 left, p2 right)

template<typename TYPE>
struct value_ref
{
typedef TYPE %_t;
};

#else
#define VALUE_CLASS(name) class name
#define OP_DECLARE(ret,name,p1,p2) \
friend ret operator ## name (p1, p2)
#define OP_DEFINE(cls,ret,name,p1,p2) \
ret operator ## name(p1 left,p2 right)

template<typename TYPE>
struct value_ref
{
typedef const TYPE &_t;
};
#endif

VALUE_CLASS(SampleClass)
{

OP_DECLARE(bool,==,value_ref<SampleClass>::_t,value_ref<SampleClass>::_t);

int value_;
};

OP_DEFINE(SampleClass,bool,==,value_ref<SampleClass>::_t,value_ref<SampleClass>::_t)
{
return left.value_ == right.value_;
}

If you've got something cleaner, please let me know. Thanks!

David Hunt
 
T

Tamas Demjen

I have a C++/CLI class I wish to have source compatible with regular
C++. I'm looking for a good way to handle the operators :

I don't think you can have a single code base for managed and unmanaged
code. The syntax is way too different, even for trivial code like yours.
If you want to write any real-world application, you'll need to use
strings and containers, where differences are even more significant. How
would you handle std::string and System::String^ with a single code
base, or std::vector<T> and List<T^>^? With STL.NET it would be somewhat
easier, but there are just enough syntactical differences that you won't
easily be able to use a single code base.

I recommend that you wrap unmanaged code into managed classes, and
provide conversion functions between them (such as enum <-> enum class,
struct <-> value struct, and so on).

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top