将class <T>转换为class <const T>的惯用方式

Yas*_*has 1 c++ idioms operator-overloading type-conversion

假设有一个模板类template <class T> myclass;

是否有惯用的方法允许将非const T对象转换为的对象const T

基本上,我希望以下转换隐式发生:

void f(myclass<const int> x);

myclass<int> a;
f(a); // should compile
Run Code Online (Sandbox Code Playgroud)

重要编辑:

答案似乎很琐碎(问题很愚蠢),但是涉及到一些概念上的问题(至少对我而言)。

I was under the impression that I need to conditionally enable a conversion operator because a conversion operator from myclass<const T> to myclass<const T> doesn't make any sense, i.e. I need to declare the conversion operator if and only if T was const qualified. I was expecting the compiler to complain about a redundant conversion operator.

Now given that the compiler is happy with the identity conversion operator which converts type X to X, what's the difference between the assignment operator or the copy constructor and the identity conversion operator?

MSVC throws a warning for an identity conversion operator. This isn't great.

Nat*_*ica 5

您可以使用返回myclass类型为const限定类型的a的转换运算符来执行此操作。看起来像

template<typename T>
struct myclass
{
    T foo;
    operator myclass<const T>() { return myclass<const T>{foo}; }
};
Run Code Online (Sandbox Code Playgroud)

然后在

int main() 
{ 
    myclass<int> a{42};
    f(a); // should compile
}
Run Code Online (Sandbox Code Playgroud)

编译器将为您隐式调用它。


如果您已经有了a myclass<const int>并将其传递给f您,则不必担心任何歧义,因为复制构造函数是完全匹配的,因此就是所谓的。但是,如果您确实想在T已经禁用转换运算符的情况const下使用,则可以使用

template<typename U = T, std::enable_if_t<!std::is_const_v<U>, bool> = true> 
operator myclass<const U>() { return myclass<const U>{foo}; }
Run Code Online (Sandbox Code Playgroud)

  • @Yashas在那种情况下,“ const崩溃”还是可以得到一个“ const T”。`myclass &lt;const int&gt;`的`operator myclass &lt;const T&gt;`将是`operator myclass &lt;const const int&gt;`,它折叠为`operator myclass &lt;const int&gt;`。 (2认同)