gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:16:42 25 4
gpt4 key购买 nike

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

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

现在我想调用这样的函数获取值()

其中函数的返回值为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

关于评估模板的 C++ 模板参数(模板模板参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25959928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com