我不是很精通模板。如何编写一个名为get的模板函数,该函数根据模板类型选择从中获取的数组?如下例所示:
struct Foo
{
int iArr[10];
char cArr[10];
// How to pick array here based on template type?
template < typename T >
T get( int idx )
{
// This does NOT work!
switch ( T )
{
case int:
return iArr[ idx ];
case char:
return cArr[ idx ];
}
}
};
// Expected behaviour of get()
Foo foo;
int i = foo.get< int >( 2 );
char c = foo.get< char >( 4 );发布于 2011-06-23 11:10:49
虽然Jason提出的解决方案有效,但它远不是惯用的,而且更难维护,因为switch语句中的case值没有明显的意义(“魔术数字”),2)很容易与switch_value<>专门化中的值不同步。我建议这样做:
struct Foo {
Foo() : iArr(), cArr() { }
template<typename T>
T get(std::size_t const idx) const {
return Foo::get_dispatcher<T>::impl(*this, idx);
}
private:
int iArr[10];
char cArr[10];
template<typename T>
struct get_dispatcher;
};
template<>
struct Foo::get_dispatcher<int> {
static int impl(Foo const& foo, std::size_t const idx) {
return foo.iArr[idx];
}
};
template<>
struct Foo::get_dispatcher<char> {
static char impl(Foo const& foo, std::size_t const idx) {
return foo.cArr[idx];
}
};使用int或char以外的任何类型调用Foo::get<>都会产生编译器错误。
发布于 2011-06-23 10:27:14
您需要添加某种类型的值结构,您可以使用它来获取switch语句的值。例如:
template<typename T>
struct switch_value {};
template<>
struct switch_value<int>
{
enum { value = 1 };
};
template<>
struct switch_value<char>
{
enum { value = 2 };
};
//then inside you structure Foo
template <typename T>
T get( int idx )
{
switch ( switch_value<T>::value )
{
case 1:
return iArr[ idx ];
case 2:
return cArr[ idx ];
}
}这里的好处是,如果您使用的类型没有有效值,这将抛出一个编译器错误,因为switch_value<T>的默认版本没有定义成员value,所以如果您没有为特定类型指定结构,那么这样的模板实例化将失败。
发布于 2013-07-31 02:23:41
所有这些答案都太夸张了。
template <typename T>
T get( int idx )
{
if ( boost::is_same<T, int>::value)
return *(T*)&iArr[ idx ];
else
return *(T*)&cArr[ idx ];
}https://stackoverflow.com/questions/6448653
复制相似问题