Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

I have this minimal, contrived example of C++ code, with a template struct with a default type 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 output (43.24). My question is, why is this necessary to do? What does the default type parameter do in the definition of AddsFourtyTwo, if you need to specify the type anyway?

like image 398
user3208090 Avatar asked Feb 03 '26 04:02

user3208090


1 Answers

You don't need to specify the type, but the language disallows using a template as an actual type without specifying some argument list:

std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;
like image 77
chris Avatar answered Feb 04 '26 17:02

chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!