我有一个模板结构,它使用模板专门化将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的类型。-我认为模板模板参数应该可以这样做。但我不确定。
我希望这是清楚的..。
提前感谢!
发布于 2014-09-21 14:02:26
template <int id>
typename IdToType<id>::Type getValue()
{
using T = typename IdToType<id>::Type;
return 65;
}DEMO
发布于 2014-09-21 14:16:59
此代码警告变量“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";
}https://stackoverflow.com/questions/25959928
复制相似问题