Why is it necessary to specify the type in this C ++ pattern?

I have this minimal, contrived example of C ++ code, with a struct template with a default parameter:

#include <iostream>
using namespace std;

template <class T=int>
struct AddsFourtyTwo {
    template <class U>
    static U do_it(U u) {
        return u + static_cast<T>(42);

int main() {
    double d = 1.24;
    std::cout << AddsFourtyTwo::do_it(d) << std::endl;


When I try to compile this code, I get the following error with g ++ 4.9.1:

$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:14:18: error: 'template<class T> struct AddsFourtyTwo' used without template parameters
     std::cout << AddsFourtyTwo::do_it(d) << std::endl;


If I specify int for T then it compiles and produces the expected result (43.24). My question is, why do you need to do this? What does the default type parameter in the definition of AddsFourtyTwo do if you need to specify the type anyway?


source to share

2 answers

You don't need to specify the type, but the language prohibits the template from being used as an actual type without specifying an argument list:

std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;




Using a template class requires the following syntax:

std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;


will compile and use the default option. This is confusing as it is not required for templated methods.



All Articles