Compilation error in template explicit specialization

S

somenath

Hi All,
I am trying to define explicit specialization for the following
template but I am getting compilation error

#ifndef COUNT_H
#define COUNT_H

template <class T,int size >
int count( const T (&array)[size],T elem)
{
int i;
int count = 0;
for ( i = 0; i<size; i++)
{
if ( array == elem )
{
count +=1;

}

}
return count;
}

template<> int count< const char * ,int size > ( const char *
(&array)[size ], const char *x) { }
#endif

File count_demo.cpp

#include <iostream>
#include "count.h"
using namespace std;
int main(void)
{
return 0;
}

g++ count_demo.cpp
In file included from count_demo.cpp:2:0:
count.h:21:16: error: parse error in template argument list
count.h:21:78: error: ‘size’ was not declared in this scope
count.h:21:84: error: expected ‘)’ before ‘,’ token
count.h:21:16: error: template-id ‘count<const char*, <expression
error> >’ for ‘int count(...)’ does not match any template declaration

If I remove the special template for const char * it compiles fine but
with the special template I am getting the following error.
Please let me know what is the mistake I am doing ?
 
Z

Zhihao Yuan

There are two problems:
template <class T,int size >
`int size' is a non-type template parameter. In an explicit
specialization, it expected to be filled in an actual constant, like

template<> int count<const char *, 20>

If you need it to be also customizable, you need partial specialization.
However, a function template does not support it, so you will finally
need a functor.
template<> int count< const char * ,int size > ( const char *
(&array)[size ], const char *x) { }

You replaced `T' with `const char *', than how about the `const T'
used in main template? That's `const char * const' actually.

The following one compiles, but as I said, you do need a functor.

template<>
int count<const char *, 20>(const char * const (&array)[20],
const char * x) { /* return sth. */ }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,930
Messages
2,570,072
Members
46,522
Latest member
Mad-Ram

Latest Threads

Top