当前位置: 首页 > 知识库问答 >
问题:

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

薛烈
2023-03-14

我想通过另一个模板参数来指定模板化函数的返回类型。所有这些都在一个类中。

在头文件中:

class MyClass {
    template<int type, typename RT>
    RT myfunc();
};
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"

共有1个答案

东门晓博
2023-03-14

这就是你要找的吗?

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"; }
 类似资料: