Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Templates - Add function only if certain value in template parameter

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;
  }
};
like image 746
keyboard Avatar asked Sep 16 '25 16:09

keyboard


1 Answers

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.

like image 183
T.C. Avatar answered Sep 19 '25 07:09

T.C.