如何解决仅在模板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;
的情况下定义这种运算符?
解决方法
一种可行的解决方案是仅在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 */ }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。