根据其他模板参数指定返回类型
Specify return type based on other template argument
我想通过另一个模板参数指定我的模板化函数的返回类型。所有这些都在课堂上。
在头文件中:
class MyClass {
template<int type, typename RT>
RT myfunc();
};
在.cpp像这样的东西:
template<>
int MyClass::myfunc<1, int>() { return 2; }
template<>
double MyClass::myfunc<2, double>() { return 3.14; }
template<>
const char* MyClass::myfunc<3, const char*>() { return "some string"; }
我希望能够像这样使用我的函数:
MyClass m;
int i = m.myfunc<1>(); // i will be 2
double pi = m.myfunc<2>(); // pi will be 3.14
const char* str = m.myfunc<3>(); // str == "some string"
所以我希望我的函数能够通过一个模板整数(或任何枚举)进行参数化,并且基于这个整数,返回类型会有所不同。我不希望该函数与指定参数以外的任何其他整数参数一起使用,例如m.myfunc<4>()
会给出编译错误。
我只想通过一个模板参数参数化我的函数,因为m.myfunc<1, int>()
可以工作,但我不想一直写类型名。
我尝试使用自动返回类型,或以其他方式模板化,但总是遇到一些编译错误。(未找到函数,未解析的外部...
这有可能吗?
这是你想要的吗?
template<int n>
struct Typer
{
};
template<>
struct Typer<1>
{
typedef int Type;
};
template<>
struct Typer<2>
{
typedef double Type;
};
template<>
struct Typer<3>
{
typedef const char* Type;
};
class MyClass
{
public:
template<int typeCode>
typename Typer<typeCode>::Type myfunc();
};
template<> Typer<1>::Type MyClass::myfunc<1>(){ return 2; }
template<> Typer<2>::Type MyClass::myfunc<2>() { return 3.14; }
template<> Typer<3>::Type MyClass::myfunc<3>() { return "some string"; }
相关文章:
- 函数作为模板参数,是否对返回类型强制约束
- 在 c++ 中将函数返回类型指定为模板参数
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 基于类型作为参数的字符串表示形式具有不同返回类型的函数
- 具有"templated"返回类型和参数的函数指针
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 如何定义依赖于参数包转换的函数的返回类型
- 无法推断返回类型的模板参数
- C++模板;作为模板参数传递的函数的自动推导返回类型
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么函数返回类型中不允许参数推导?
- 模板化函数以从输入参数推断返回类型 stl-container
- 将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型
- C++ 如何将参数绑定到具有相同返回类型的函数,并将它们全部存储在一个容器中
- 为什么编译器不能从返回类型中推断出模板参数?
- 具有不同模板参数的函数返回类型
- C++:返回类型为 T 的模板函数不带 T 类型参数,将无法编译