无法将模板参数 this 替换为类型模板参数 _Ty

Cannot substitute template argument this for type template parameter _Ty

我试图通过使用静态断言来禁止创建 const MyClass 类型。当声明 class const 时,this 关键字的类型为 const MyClass* 所以我认为这会起作用

class MyClass
{
    static_assert(std::is_const_v<std::remove_pointer_t<this>>, "Can't create const MyClass");
}

但是我收到以下错误Cannot substitute template argument this for type template parameter _Ty

为什么我的 static_assert 表达不合法?

您不能在 static_assert 的上下文中使用 this。你可以把它放在一个虚拟成员函数中,但这不会做你试图阻止的事情,因为成员函数内部 this 的类型取决于成员的 const 限定符函数。

这也是一件很奇怪想做的事情。我不知道你为什么要那样做。

简单的解决方法是用 const 标记零个函数,这样 const 对象就不能实际调用任何函数。它并不完美,但你不能做得更好。

std::remove_pointer_t<> 需要类型,但 this 是指针,而不是类型。

您需要的是 std::is_const_v<std::remove_pointer_t<decltype(this)>>,但这也不会起作用,因为您不能在非静态成员函数之外使用 this

据我所知,没有办法阻止 const 限定对象的创建。