2

Can anyone describe the following declaration?

template<> float func<float>(char *txt)
{
blah blah 
}

What is the second <> for?

2 Answers 2

13

The template<> means that this function is a template specialization. The second <float> means that this is the specialization for float.

For example:

#include <iostream>

template <class T> void somefunc(T arg) {
    std::cout << "Normal template called\n";
}

template<> void somefunc<float>(float arg) {
    std::cout << "Template specialization called\n";
}

int main(int argc, char *argv[]) {
    somefunc(1); // prints out "Normal template called"
    somefunc(1.0f); // prints out "Template specialization called"

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

2

This is a specialized template function. It happens when you try to specialized a generic template function. Usually you will have another deceleration as

template<typename T> float func(char *txt) {
    T vars[1024];
    blah blah
}

It happens sometime you want to do a specialized declaration for certain type T. In previous example, if T is bool type, you might want to change the behavior of vars array to save some space (because each bool entry might still take 32bits).

template<> float func<bool>(char *txt) {
    int vars[32];
    blah blah
}

By defining a specialized version, you are allowed to manipulate the vars array in bit-wise manner.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.