Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator() template specialization

Tags:

c++

templates

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.

like image 308
Ran Drori Avatar asked Dec 29 '11 14:12

Ran Drori


1 Answers

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.

like image 122
Dietmar Kühl Avatar answered Sep 22 '22 18:09

Dietmar Kühl