Eoi*_*oin 10 c++ templates partial-specialization template-specialization
我有一个带有类型和非类型模板参数的模板类.我想专门化一个成员函数,我发现的是,如下例所示,我可以完全专业化.
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;
}
Run Code Online (Sandbox Code Playgroud)
但是这种部分特化不会编译.
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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法实现我试图让任何人知道的东西?我在MSVC 2010中试过这个.
Pot*_*ter 12
您可以将函数包装在类中.
只有类,而不是函数,可能是部分专用的.
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;
}
};
Run Code Online (Sandbox Code Playgroud)