Reputation: 181
#include <iostream>
template<typename T, int = 0>
struct test {
typedef char type[3];
};
template<int N>
struct test<long *, N> {
typedef char type[7];
};
int main()
{
std::cout << sizeof( test<int*>::type ) << std::endl; // 3
std::cout << sizeof( test<long*>::type ) << std::endl; // 7
return 0;
}
I expected sizeof( test<long*>::type ) == 3
. Why it is 7?
Upvotes: 2
Views: 83
Reputation: 96311
You specialized your template so that if the type argument is long*
then the size is changed. I'm fairly sure you can't mix the test<int*>
and test<123>
forms that you want to use (what would the meaning be of a parameter that could be either a type OR a value?). The best you can do is something like:
#include <iostream>
template<typename T, int = 0>
struct test {
typedef char type[3];
};
template<int N>
struct test<int, N> {
typedef char type[7];
};
int main()
{
std::cout << sizeof( test<int*>::type ) << std::endl; // 3
std::cout << sizeof( test<long*>::type ) << std::endl; // 3
std::cout << sizeof( test<int, 123>::type ) << std::endl; // 7
return 0;
}
Maybe if you tell us the real problem you're trying to solve that would help.
Upvotes: 1
Reputation: 21123
What you did is you specialized the template, saying that whenever the type argument is long*
, you should use the second form of the template. For other arguments, it will use the initial form of the template (with size 3).
Upvotes: 3