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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With