仅当模板 arg 不是 const 时才定义 C++ 转换运算符

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

我正在编写从 CContainer<CLASS>CContainer<const CLASS> 的自定义转换运算符。代码如下所示:

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

技术上 它运行良好,但有些编译器每次在显式实例化时都会打印警告,如 operator CContainer<const T>() const will never be used使用常量模板参数,例如 CContainer<const float> constFloatContainer;.

有没有办法避免这个警告,并且只在 C++11T 不是 const 时定义这样的运算符?

一种可能的解决方案是仅当 T 不同于 T const 时使用 SFINAE 来启用运算符。

例如(注意:代码未经测试)

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 */ }

或者,按照 Remy Lebeau 的建议(谢谢),您可以使用 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 */ }