用于评估模板的C++模板参数(模板模板参数)

C++ Template Parameter that evaluates a Template (template template parameter)

本文关键字:参数 评估 用于 C++      更新时间:2023-10-16

我有一个模板化结构,它使用模板专业化将ID映射到类型(取自https://www.justsoftwaresolutions.co.uk/articles/exprtype.pdf)。

template<int id>
struct IdToType
{};
template<>
struct IdToType<1>
{
typedef bool Type;
};
template<>
struct IdToType<2>
{
typedef char Type;
};

现在我想调用这样的函数getValue()

其中函数的返回值是ID的相应类型。

template</*.... I don't know what to put here...*/ T>
idToType<T>::Type getValue() // I don't know exactly how to define the return value
{
    // whant to do some things with the provided ID and with the type of the id
}

简而言之:-我想要一个模板函数,在这里我可以使用ID作为模板参数。-函数需要将ID对应的类型作为返回值(我从IdToType::type中获得对应的类型)。-在函数的主体中,我希望能够访问ID和ID的类型。-我认为这应该是可能的模板模板参数。但我不确定。

我希望这是非常清楚的。。。

提前感谢!

template <int id>
typename IdToType<id>::Type getValue() 
{
    using T = typename IdToType<id>::Type;
    return 65;
}

DEMO

此代码警告变量"val"未使用。但是,由于我们不想对getValue()中的类型做什么,所以我就这样留下了代码。

char getValueImpl(char)
{
    return 'c';
}

bool getValueImpl(bool)
{
    return true;
}
template<int X>
typename IdToType<X>::Type getValue()
{
    typename IdToType<X>::Type val;
   return getValueImpl(val);
}

int main()
{
   std::cout << getValue<2>() << "n";
   std::cout << getValue<1>() << "n";
}