我可以从模板类中提取C ++模板参数吗? [英] Can I extract C++ template arguments out of a template class?
问题描述
基本上,给定一个这样的模板类:
Basically, given a template class like this:
template< class Value > class Holder { };
我想能够发现 Value
给予 Holder
类。我想我将能够做一个简单的元功能,它接受一个模板模板参数,如下:
I would like to be able to discover the type Value
for a given Holder
class. I thought that I would be able to make a simple metafunction that takes a template template argument, like this:
template< template< class Value > class Holder > class GetValue
{
typedef Value Value;
};
然后提取 Value
this:
GetValue< Holder< int > >::Value value;
但是我只是得到一个指向metafunction声明的错误信息:
But instead I just get an error message pointing to the metafunction declaration:
error: ‘Value’ does not name a type
b $ b
有没有办法完成这种事情?感谢。
Is there any way to accomplish this kind of thing? Thanks.
我也收到错误讯息:
error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class Value> class Holder> class GetValue’
error: expected a class template, got ‘Holder<int>’
推荐答案
为什么我们不能将类作为模板模板参数传递?不要只是将持有人类别更改为
Why don't you simply change your holder class to
template< class Value > class Holder {
typedef Value value_type;
value_type m_val; // member variable
};
在任何消耗类型为Holder < T>您可以访问所包含的类型:
In any method that consumes an object of type Holder< T > you can access the contained type like that:
template< class THolder >
void SomeMethod( THolder const& holder ) {
typename THolder::value_type v = holder.m_val;
}
此方法遵循所有STL类使用的模式,例如std :: vector< ; int> :: value_type是int。
This approach follows the pattern all STL classes use, e.g., std::vector< int >::value_type is int.
我想你正在尝试部分模板专业化:
I think you're trying to do partial template specialization:
template<class T>
class GetValue {
};
template<class Value>
class GetValue< Holder<Value> > {
public:
typedef Value value_type;
};
在您的代码中,您可以执行以下操作:
In your code, you could then do the following:
template<class THolder>
void SomeMethod( THolder const& h ) {
typename GetValue< THolder >::value_type v = h.m_v;
}
一般来说,我更喜欢第一个解决方案。
In general, I'd prefer the first solution though.
这篇关于我可以从模板类中提取C ++模板参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!