gpt4 book ai didi

c++ - 仅当模板参数不是 const 时才定义 C++ 转换运算符

转载 作者:行者123 更新时间:2023-12-01 14:38:49 25 4
gpt4 key购买 nike

我正在编写来自 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; .

有没有办法避免此警告,并仅在 T 时定义这样的运算符不是constC++11中?

最佳答案

一个可能的解决方案是仅当 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 */ }

关于c++ - 仅当模板参数不是 const 时才定义 C++ 转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63731036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com