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

Fed*_*inV 2 c++ templates type-conversion template-meta-programming c++11

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

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

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

是否有办法避免这种警告,并这样定义运营商,只有当T没有constC ++ 11

max*_*x66 5

一种可能的解决方案是使用 SFINAE 仅在T与 不同时启用运算符T const

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

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 */ }
Run Code Online (Sandbox Code Playgroud)

或者,按照 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 */ }
Run Code Online (Sandbox Code Playgroud)