0

For the below code, I got some compiling errors and don't know why.

~/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
       ^

Code:

/* 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;
}

UPDATED: My own answer

According the standard 14.5.5.3

A class template specialization is a distinct template. The members of the class template partial specialization are unrelated to the members of the primary template.

That is to say the primary class template Search_A_Scale<A, B, C> is distinct with the class template partial specialization Search_A_Scale<A, 0, C>, so the specified member Search_A_Scale<A, 0, C>::operator() requires a definition of the Search_A_Scale<A, 0, C> but which is missed.

Yantao Xie
  • 12,300
  • 15
  • 49
  • 79
  • You can't partially specialize a member function. Will have to dig up the appropriate section of the standards document to provide concrete reference. – R Sahu May 20 '14 at 04:00
  • 1
    Take a look at this [answer to an SO post](http://stackoverflow.com/a/15378899/434551). – R Sahu May 20 '14 at 04:02

1 Answers1

0

The function in #if looks like member function of

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

You should change the declaration in "#if" as :

#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;
}

When we use Search_A_Scale this as scope resolution compiler should find

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

as candidate but the template specification in your function is

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

and there is no class defined which takes 2 params, it exist when else part of #if condition: template class Search_A_Scale

Hence when we execute the else part we get a class specialized to take three params of type A, 0 and C.

Nik
  • 1,294
  • 10
  • 16