繁体   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