Is what I'm trying here possible somehow?
I know that #if doesn't work with template parameters.
Please don't teach me how properties are against the idea of C++, that's not the question here.
typedef enum {
kPropertyReadWrite,
kPropertyReadOnly
} PropertyType;
template <typename T, PropertyType P = kPropertyReadWrite>
class property {
  T value;
public:
  property() {}
  property(T initValue) : value(initValue){}
#if P == kPropertyReadOnly
  T & operator = (const T &i) {
    //::std::cout << i << ::std::endl;
    return value = i;
  }
#endif
  operator T const & () const {
    return value;
  }
};
I'm surprised that so many people can't get the SFINAE right. The SFINAE condition needs to depend on a template parameter of operator=, and not the class template. Otherwise, instantiating the class template may cause a hard error.
template<PropertyType P1 = P, typename std::enable_if<P1 != kPropertyReadOnly, int>::type = 0>
T & operator = (const T &i) {
  //::std::cout << i << ::std::endl;
  return value = i;
}
Note that this is actually not sufficient to prevent property<int, kPropertyReadOnly> p2; p2 = 10; from compiling, because your code defines an implicit conversion from T to property<T, ...>, so the compiler will implicitly convert the 10 to a property and then call the copy assignment operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With