依赖函数模板参数



假设我希望函数模板的返回值由some-template参数确定。我可以使用auto:

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

然而,我不清楚如果没有auto,这是怎么可能的。假设我的函数模板是:

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

要使用它,我现在需要指定这两个参数。有办法解决这个问题吗?我想对于一个类,我可以使用第二个参数的默认值进行部分专门化,但不能使用函数。

无论如何,都不确定自己到底想要什么。。。

如果没有auto,我想您可以添加一些从整数(或枚举(值传递到请求的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 ()
{ /* ... */ }

最新更新