I've been struggling with NOT C++0x code, but regular C++. Don't ask me why I have to use regular C++, it's just some kind of silly requirement.
So here's the thing : I need to get a value in an enum to be 1 or 0, regarding that some statement is true or false. So of course, I templated a struct containing 0 in an enum, specializated it with the second statement where the enum contains 1 instead of 0.
Seems quite legit to me, however, it tells me that I should use the parameters of the specialization. Which is kinda strange, because I tried to use it in all possible ways and it just kept popping out this error.
Here's the code :
template<typename T>
struct CanPrint
{
template<size_t>
struct Value { enum { val = 0 }; };
template<size_t>
struct Value<sizeof(True)> { enum { val = 1 }; };
enum
{ value = Value<sizeof(IsTrue<T>(0))>::val };
};
I bet this would work if it wasn't a partial specialization, but explicit ones can't be at namespace-sc开发者_如何学Cope. And I obviously can't specialize a template within a template without specializing both of them. Can I ?
template<> //<---- leave it empty
struct Value<sizeof(True)> { enum { val = 1 };
By the way, its not partial specialization if True
isn't template argument. It is full specialization .
And since this is full specialization, you cannot define it inside the class, i.e at class-scope. Full specialization can be defined only at namespace-scope. So define Value
, primary well as the specialization, at namespace scope.
Or, you can do this instead:
template<typename T>
struct CanPrint
{
//modified
template<typename U, size_t N = sizeof(U)>
struct Value { enum { val = 0 }; };
//modified - now its partial specialization
template<typename U>
struct Value<U, sizeof(True)> { enum { val = 1 }; };
enum { value = Value<IsTrue<T> >::val }; //modified here as well
};
See the online demo : http://www.ideone.com/MSG5X
template<> // note the empty <>
struct Value<sizeof(True)> { enum { val = 1 }; };
You only list parameters for partial specializations:
template< typename T, typename U>
struct X;
template<typename U>
struct X<char,U> {...};
template<typename Z, typename U>
struct X<std::vector<Z>, U> {...};
Not for full specializations:
template<>
struct X<double,int> {...};
精彩评论