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

问题描述

我正在将自定义转换运算符从set.seed(11) N = 1000 v = rep(c('a','b','c','d'),N/4) probs <- c(a=.8,b=.6,c=.4,d=.1) x <- runif(N) < probs[v] tapply(x,v,mean) # a b c d # 0.780 0.604 0.376 0.120 转换为CContainer<CLASS>代码如下:

CContainer<const CLASS>

技术上 都可以很好地工作,但是某些编译器每次在存在带有常量模板参数的显式实例化时都打印警告template<class T> class CContainer { public: operator CContainer<const T>() const { /* here goes the code */ } }; ,例如{{ 1}}。

有没有一种方法可以避免这种警告,并且仅在 C ++ 11 operator CContainer<const T>() const will never be used不是CContainer<const float> constFloatContainer;的情况下定义这种运算符?

解决方法

一种可行的解决方案是仅在TT 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 */ }