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

Specify return type based on other template argument

我想通过另一个模板参数指定我的模板函数的 return 类型。所有这些都在 class.

在头文件中:

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"

所以我希望我的函数能够由一个模板整数(或任何枚举)参数化,并且 return 类型会有所不同,基于这个整数。 我不希望该函数使用指定参数以外的任何其他整数参数,例如这里 m.myfunc<4>() 会产生编译错误。

我只想通过一个模板参数来参数化我的函数,因为 m.myfunc<1, int>() 可以工作,但我不想一直写类型名。

我尝试使用自动 return 类型,或以其他方式进行模板化,但总是遇到一些编译错误。 (未找到函数,未解决的外部问题...)

这有可能吗?

这是你要的吗?

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