【发布时间】:2023-03-20 15:58:01
【问题描述】:
对于下面的代码,我遇到了一些编译错误,不知道为什么。
~/sandbox/test-cxx $ g++ test-template-specialization.cpp
test-template-specialization.cpp:23:12: error: invalid use of incomplete type ‘class Search_A_Scale<A, 0, C>’
operator()()
^
test-template-specialization.cpp:8:7: error: declaration of ‘class Search_A_Scale<A, 0, C>’
class Search_A_Scale
^
代码:
/* test-template-specialization.cpp */
#include <iostream>
#include <string>
using namespace std;
template <int A,
int B,
int C>
class Search_A_Scale
{
public:
bool operator()();
enum {
kb = B,
kc = C
};
};
#if 1 // this block cimpiled failed.
template <int A,
int C>
bool Search_A_Scale<A, 0, C>::
operator()()
{
return true;
}
#else // this block compiled successfully.
template <int A, int C>
class Search_A_Scale<A, 0, C>
{
public:
bool operator() () { return true; }
};
#endif
int main()
{
Search_A_Scale<1, 0, 24> a;
cout << a() << endl;
return 0;
}
已更新:我自己的回答
根据标准 14.5.5.3
类模板特化是一个独特的模板。的成员 类模板部分特化与成员无关 的主模板。
也就是说主类模板Search_A_Scale<A, B, C>与类模板部分特化Search_A_Scale<A, 0, C>是不同的,所以指定的成员Search_A_Scale<A, 0, C>::operator()需要Search_A_Scale<A, 0, C>的定义,但是漏掉了。
【问题讨论】:
-
您不能部分特化成员函数。必须挖掘标准文档的适当部分以提供具体参考。
-
看看这个answer to an SO post。