5
votes

I'm trying to do specialization to template operator, the template looks like this:

 template <typename Iterator1, typename Iterator2>
ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const

after i did the specialization that looks like this:

template <>
float operator()<float*,float*>(float* a, float const* b, unsigned long size, float worst_dist = -1) const

i get an error during compilation :

Cannot specialize a function 'operator()' within class scope

All those function are in struct template

I'll be glad to get some help. thanks.

1
When you say "specification", do you mean, "specialization"? - Marcelo Cantos
I think that [this SO question/answer][1] might be answering what you are trying to do. [1]: stackoverflow.com/questions/4920068/… - wilx
What is ResultType? Is it supposed to be one of your template parameters? - Alan Stokes
Where exactly do these two declarations occur? As the message suggests you aren't allowed to specialize a function inside a class definition. - Alan Stokes
@Ran Then your specialization doesn't match the template you're trying to specialize - and it has to. You have unsigned long instead of size_t for the size parameter and float instead of ResultType for worst_dist. - Alan Stokes

1 Answers

11
votes

Why do you want to specialize this operator anyway? You won't be able to call it using the syntax which depends on specializations (i.e. explicit providing the [some of] the template arguments) anyway! Just use overloading and you should be fine. Although it is sometimes desirable or even necessary to use the notation where you explicitly specify the template arguments, it tends to be not that important for functions in general to use specialization rather than overloading.

I just read things up in the standard and actually is possible to provide an explicit specialization, however it has to be outside of the class definition. For example:

#include <iostream>

struct foo
{
    template <typename T> void operator()(T const&) {
        std::cout << "general\n";
    }
};

template <>
void foo::operator()<int>(int const&) {
    std::cout << "int spec\n";
}

int main()
{
    foo f;
    f(1.2);
    f(1);
    f<double>(1); // <-- ERROR: doesn't work!
}

This would have worked the same using overloading. Using explicitly specified template arguments still doesn't work, though.