【问题标题】:Why my partial template specialization of a class member function got compiling error? [duplicate]为什么我的类成员函数的部分模板特化出现编译错误? [复制]
【发布时间】: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&lt;A, B, C&gt;与类模板部分特化Search_A_Scale&lt;A, 0, C&gt;是不同的,所以指定的成员Search_A_Scale&lt;A, 0, C&gt;::operator()需要Search_A_Scale&lt;A, 0, C&gt;的定义,但是漏掉了。

【问题讨论】:

  • 您不能部分特化成员函数。必须挖掘标准文档的适当部分以提供具体参考。
  • 看看这个answer to an SO post

标签: c++ templates


【解决方案1】:

#if 中的函数看起来像

的成员函数
template <int A, int B, int C>
class Search_A_Scale

您应该将“#if”中的声明更改为:

#if 1 // this block changed,which was failing earlier
template <int A, int B, int C>
bool Search_A_Scale<A, B, C>::operator()()
{
    return true;
}

当我们使用 Search_A_Scale 这个作为范围解析编译器应该找到

template <int A, int B, int C> 
class Search_A_Scale 

作为候选,但您的函数中的模板规范是

template <int A,int C>
bool Search_A_Scale<A, 0, C>::operator()()

并且没有定义需要 2 个参数的类,它存在于 #if 条件的 else 部分: 模板 类 Search_A_Scale

因此,当我们执行 else 部分时,我们会得到一个专门用于获取 A、0 和 C 类型的三个参数的类。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 1970-01-01
    • 2018-01-23
    • 2013-02-28
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多