Define C++ conversion operator only if template arg is not const

Viewed 106

I'm writing custom conversion operator from CContainer<CLASS> to CContainer<const CLASS>. The code looks like this:

template<class T>
class CContainer
{
public:
    operator CContainer<const T>() const { /* here goes the code */ }
};

and technicaly it works well, but some compilers print warnings like operator CContainer<const T>() const will never be used each time when there is an explicit instantiation with constant template argument, like CContainer<const float> constFloatContainer;.

Is there a way to avoid this warning, and define operators like this only when T is not const in C++11?

1 Answers

A possible solution is use SFINAE to enable the operator only when T is different from T const.

For example (caution: code not tested)

template <typename U = T,
   typename std::enable_if<false == std::is_same<U, T const>::value, int>::type = 0>
operator CContainer<U const>() const
 { /* here goes the code */ }

or, as suggested by Remy Lebeau (thanks) you can use std::is_const

template <typename U = T,
   typename std::enable_if<false == std::is_const<U>::value, int>::type = 0>
operator CContainer<U const>() const
 { /* here goes the code */ }
Related