ano*_*non 10 c++ templates partial-specialization template-specialization
码:
template<class T>
struct A {
void f1() {};
void f2() {};
};
template<>
struct A<int> {
void f2() {};
};
int main() {
A<int> data;
data.f1();
data.f2();
};
Run Code Online (Sandbox Code Playgroud)
test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'
Run Code Online (Sandbox Code Playgroud)
基本上,我只想专门化一个函数并使用其他函数的通用定义.(在实际代码中,我有许多我不想专门研究的函数).
这该怎么做?谢谢!
Ale*_* C. 10
考虑将公共部分移动到基类:
template <typename T>
struct ABase
{
void f1();
};
template <typename T>
struct A : ABase<T>
{
void f2();
}
template <>
struct A<int> : ABase<int>
{
void f2();
};
Run Code Online (Sandbox Code Playgroud)
您甚至可以f1在派生类中覆盖.如果你想做一些更奇特的事情(包括能够f2从f1基类中的代码调用),请查看CRTP.
这有用吗:
template<typename T>
struct A
{
void f1()
{
// generic implementation of f1
}
void f2()
{
// generic implementation of f2
}
};
template<>
void A<int>::f2()
{
// specific implementation of f2
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3255 次 |
| 最近记录: |