[英]'std::map' : 'SomeClass' is not a valid template type argument for parameter '_Ty'
[英]Cannot substitute template argument this for type template parameter _Ty
我試圖通過使用靜態斷言來禁止創建const MyClass
類型。 當一個類被聲明為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
表達式不合法?
std::remove_pointer_t<>
需要一個類型,但是this
是一個指針,而不是一個類型。
你需要的是std::is_const_v<std::remove_pointer_t<decltype(this)>>
但是它不能正常工作,因為你不能在非靜態成員函數之外使用this
。
據我所知,沒有辦法停止創建一個const限定對象。
您不能在static_assert
的上下文中使用this
。 你可以把它放在一個虛成員函數,但不會做你試圖阻止什么,因為類型this
成員函數內依賴於const
的成員函數的修飾詞。
這也是一件很奇怪的事情。 我不知道你為什么要那樣做。
簡單的解決方法是使用const
標記零函數,以便const
對象實際上不能調用任何函數。 它並不完美,但你不能做得更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.