具有非类型参数的成员函数的部分专业化 [英] Partial specialisation of member function with non-type parameter
本文介绍了具有非类型参数的成员函数的部分专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个同时具有类型和非类型模板参数的模板类.我想对成员函数进行专业化处理,我发现,如下面的示例所示,我可以进行完全的专业化处理.
I have a template class with both a type and a non-type template parameter. I want to specialize a member function, what I finding is, as in the example below, I can do a full specialization fine.
template<typename T, int R>
struct foo
{
foo(const T& v) :
value_(v)
{}
void bar()
{
std::cout << "Generic" << std::endl;
for (int i = 0; i < R; ++i)
std::cout << value_ << std::endl;
}
T value_;
};
template<>
void foo<float, 3>::bar()
{
std::cout << "Float" << std::endl;
for (int i = 0; i < 3; ++i)
std::cout << value_ << std::endl;
}
但是这种部分专业化不会编译.
However this partial specialization won't compile.
template<int R>
void foo<double, R>::bar()
{
std::cout << "Double" << std::endl;
for (int i = 0; i < R; ++i)
std::cout << value_ << std::endl;
}
有没有一种方法可以实现我正在尝试的任何人都知道的?我在MSVC 2010中尝试过.
Is there a way to achieve what I'm attempting would anyone know? I tried this in MSVC 2010.
推荐答案
您可以将函数包装在类中.
You can wrap the function inside a class.
仅类(而不是函数)可能是部分专用的.
Only classes, not functions, may be partially specialized.
template<typename T, int R>
struct foo
{
foo(const T& v) :
value_(v)
{}
void bar()
{
return bar_impl< T, R >::bar( * this );
}
friend struct bar_impl< T, R >;
T value_;
};
template< typename T, int R >
struct bar_impl {
static void bar( foo< T, R > &t ) {
std::cout << "Generic" << std::endl;
for (int i = 0; i < R; ++i)
std::cout << t.value_ << std::endl;
}
};
template<>
struct bar_impl<float, 3> {
static void bar( foo< float, 3 > &t ) {
std::cout << "Float" << std::endl;
for (int i = 0; i < 3; ++i)
std::cout << t.value_ << std::endl;
}
};
template<int R>
struct bar_impl<double, R> {
static void bar( foo< double, R > &t ) {
std::cout << "Double" << std::endl;
for (int i = 0; i < R; ++i)
std::cout << t.value_ << std::endl;
}
};
这篇关于具有非类型参数的成员函数的部分专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文