簡體   English   中英

具有非類型模板參數的功能模板中的static_assert

[英]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_valuefunction<int T>進行有效實例化。


還有一個不涉及static_assert的簡單解決方案:

template <int T> void function() = delete;

當我第一次回答這個問題時,我不明白原始代碼是什么問題,但是現在,由於其他受訪者的支持,我做到了,所以這一切都值得。

無論如何,一個顯而易見的解決方案是將三個模板替換為:

template <int T>
void function() {
    static_assert(T == 1, "Error");
};

在gcc可以正常工作

順便說一下,clang和MSVC仍然可以成功地編譯原始代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM