根据参数返回类型
Returning a type depending on the parameter
我想具有这样的函数,以至于它的返回类型将在函数中确定(取决于参数的 value ),但未能实现它。(也许模板专业化?)
// half-pseudo code
auto GetVar(int typeCode)
{
if(typeCode == 0)return int(0);
else if(typeCode == 1)return double(0);
else return std::string("string");
}
我想使用它而不指定类型为:
auto val = GetVar(42); // val's type is std::string
不起作用,您必须在编译时给出参数。以下将有效:
template<int Value>
double GetVar() {return 0.0;};
template<>
int GetVar<42>() {return 42;}
auto x = GetVar<0>(); //type(x) == double
auto y = GetVar<42>(); //type(x) == int
另一个版本是通过std :: integnal_constant,诸如此类:
template<int Value>
using v = std::integral_constant<int, Value>;
template<typename T>
double GetVar(T) {return 0;};
int GetVar(v<42>) {return 42;};
auto x = GetVar(v<0>()); //type(x) == double
auto y = GetVar(v<42>()); //type(x) == int
由于C 是面向对象的,我们可以从父类中继承所有选项,然后返回该父类的实例。
另外,我们可以尝试void *返回类型。
#include <type_traits>
#include <iostream>
// foo1 overloads are enabled via the return type
template<class T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type
foo1(T t)
{
std::cout << "foo1: floatn";
return t;
}
来自C 17,也可以使用if constexpr
在问题中保留与代码相似的结构:
template<int typeCode>
auto GetVar()
{
if constexpr(typeCode == 0) return int(0);
else if constexpr(typeCode == 1) return double(0);
else return std::string("string");
}
相关文章:
- 函数作为模板参数,是否对返回类型强制约束
- 在 c++ 中将函数返回类型指定为模板参数
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 基于类型作为参数的字符串表示形式具有不同返回类型的函数
- 具有"templated"返回类型和参数的函数指针
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 如何定义依赖于参数包转换的函数的返回类型
- 无法推断返回类型的模板参数
- C++模板;作为模板参数传递的函数的自动推导返回类型
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么函数返回类型中不允许参数推导?
- 模板化函数以从输入参数推断返回类型 stl-container
- 将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型
- C++ 如何将参数绑定到具有相同返回类型的函数,并将它们全部存储在一个容器中
- 为什么编译器不能从返回类型中推断出模板参数?
- 具有不同模板参数的函数返回类型
- C++:返回类型为 T 的模板函数不带 T 类型参数,将无法编译