![](/img/trans.png)
[英]How to static_assert that type is viable for template non-type parameter in c++20
[英]static_assert in function template with non-type template parameter
我有一個帶有整數模板參數的函數模板。 我只想提供特定整數的實現。 嘗試將函數模板與其他參數一起使用會導致編譯錯誤。
我以下面介紹的方式使用了static_assert
。
#include <type_traits>
#include <iostream>
template <typename T>
struct false_type : public std::false_type {};
template <int T>
void function() {
static_assert(false_type<decltype(T)>::value, "Error");
};
template <>
void function<1>() {
std::cout << 1 << std::endl;
}
int main() {
function<1>();
}
該代碼在gcc 9.1
給出error: static assertion failed
之前一直運行良好error: static assertion failed
。
我想知道是否有一種技術可以實現我的目標並且與gcc 9.1
兼容?
即使在從未實例化的模板中,其第一個參數是不相關的虛假常量的static_assert
始終“ static_assert
錯誤,無需診斷”。 (因此,g ++和clang ++都不是“不正確的”。)在您的函數模板中, T
依賴於值,但不依賴於類型(其類型始終為int
),因此decltype(T)
不依賴於, false_type<int>::value
。
您false_type
只將false_type
也接受一個int
作為參數?
#include <type_traits>
#include <iostream>
template <int>
struct false_type : public std::false_type {};
template <int T>
void function() {
static_assert(false_type<T>::value, "Error");
};
template <>
void function<1>() {
std::cout << 1 << std::endl;
}
int main() {
function<1>();
}
GCC 9.1似乎認識到false_type<decltype(T)>::value
實際上並不依賴於T
,這使它可以及早評估條件(第一次看到模板false_type<decltype(T)>::value
不是實例化時)。
這是一種解決方法:
template <auto V, auto...> inline constexpr auto dependent_value = V;
template <int T>
void function()
{
static_assert(dependent_value<false, T>, "Error");
}
這樣,編譯器必須實例化function<T>
來評估dependent_value<false, T>
(因為在定義function<T>
之后 ,可以對dependent_value
進行專門化處理)。
請注意,由於無法為function<int T>
實現生成有效的實例化,因此問題中的代碼格式不正確,不需要進行診斷 。
此解決方法沒有此問題,因為您可以通過先專門化dependent_value
對function<int T>
進行有效實例化。
還有一個不涉及static_assert
的簡單解決方案:
template <int T> void function() = delete;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.