C++ 依赖函数模板参数

C++ 依赖函数模板参数,c++,c++17,C++,C++17,假设我希望函数模板的返回值由sometemplate参数确定。我可以使用auto: template<int> auto foo2(); template<> auto foo2<5>() { return std::make_optional(5.0); } 要使用它,我现在需要指定这两个参数。这有什么办法吗?我想对于一个类,我可以使用第二个参数的默认值进行部分专门化,但不能使用函数。无论如何,我不确定您到底想要什么 如果没有auto,我想您可以

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

template<int>
auto foo2();

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

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

无论如何,我不确定您到底想要什么

如果没有
auto
,我想您可以添加一些内容,以便从整数(或枚举)值传递到请求的
T
类型

例如。。。您可以添加自定义类型trait,如下所示

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; };
当您的
int
值从零开始并且是连续的时,您可以使用
std::tuple
,而不是自定义类型

我想象着

template<int I>
std::optional<typename get_type<I>::type> foo ()
 { /* ... */ }
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 ()
 { /* ... */ }
使用type_list=std::tuple;
模板
std::可选的foo()
{ /* ... */ }

但是有一条规则可以根据
int
值?@max66排序来确定
T
类型。不是
int
,而是一个枚举,每个枚举值映射到某个类。
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 ()
 { /* ... */ }