根据其他模板参数指定返回类型

时间:2015-01-06 22:28:21

标签: c++ templates return-type function-templates

我想通过其他模板参数指定模板化函数的返回类型。所有这一切都在一个班级内。

在头文件中:

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>()会起作用,但我不想一直写出类型名。

我试过自动返回类型,或者以其他方式模板化,但总是遇到一些编译错误。 (找不到功能,未解决的外部......)

这有可能吗?

1 个答案:

答案 0 :(得分:2)

这是你寻求的吗?

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"; }