簡體   English   中英

依賴 function 模板參數

[英]Dependent function template parameter

假設我希望 function 模板的返回值由某個模板參數確定。 我可以使用auto

template<int>
auto foo2();

template<>
auto foo2<5>() {
    return std::make_optional(5.0);
}

但是,我不清楚沒有auto怎么可能。 假設我的 function 模板是:

template<int, typename T>
std::optional<T> foo();

template<>
std::optional<double> foo<5, double>() {
    return std::make_optional(5.0);
}

要使用它,我現在需要指定兩個參數。 有沒有辦法解決? 我想使用 class 我可以使用第二個參數的默認值進行部分專業化,但不能使用 function。

不知道你到底想要什么,反正......

如果沒有auto ,我想您可以添加一些東西以從 integer (或枚舉)值傳遞給請求的T類型。

例如...您可以添加自定義類型特征,如下所示

template <int>
struct get_type;

template <>
struct get_type<0>
 { using type = int; };

template <>
struct get_type<1>
 { using type = long; };

template <>
struct get_type<5>
 { using type = double; };

所以foo()變成了

template<int I>
std::optional<typename get_type<I>::type> foo ()
 { /* ... */ }

當您的int值從零開始並且是連續的時,您可以使用std::tuple而不是自定義類型特征。

我想像

using type_list = std::tuple<char, int, long, long long, float, double>;

template <std::size_t I>
std::optional<std::tuple_element_t<I, type_list>> foo ()
 { /* ... */ }

暫無
暫無

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

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