I'am wondering whether it is possible to access type definitions of types which are given as previous template parameters in later template parameters in a template parameter list like so:
#include <iostream>
template<typename V>
struct TypeHolder {
typedef V value_type;
开发者_如何学Go};
template<typename T, T::value_type v>
struct ValueHolder {
const static typename T::value_type value = v;
};
int main() {
typedef TypeHolder<int> IntTypeHolder;
typedef ValueHolder<IntTypeHolder,5> Five;
std::cout << Five::value << std::endl;
return 0;
}
When I compile the above example I get the following error:
damian@damian-HP-EliteBook-8440p:~$ g++ -o cpptest test.cpp
test.cpp:8:25: error: 'T::value_type' is not a type
Is this due to wrong syntax or is what I'm trying to do just not possible in c++?
It's possible. You are missing the keyword typename
.
template<typename T, typename T::value_type v>
struct ValueHolder { ^^^^^^^^
...
You have to inform the compiler that T::value_type
is a type.
Demo.
If you prefix typename
to the template parameter it compiles:
template<typename T, typename T::value_type v>
struct ValueHolder {
const static typename T::value_type value = v;
}
The use of typename
helps the compiler know that in this case the identifier value_type
referenced within the T::
namespace is a type and not a member function or variable.
Try the following:
template<typename T, typename T::value_type v>
struct ValueHolder {
const static typename T::value_type value = v;
};
You for got to prefix "typename" to your T:value_type
... unfortunately just because value_type
is a typedef
member of T
does not mean that the C++ parser can tell. It may be an actual static data member, static method, etc. Therefore when accessing fully-qualified types in other namespaces/classes, you have to prefix them with typename
.
It is due to wrong syntax, what you try to do with T::value_type v
is to get a value right?
Then better use something like that :
template<typename T>
struct ValueHolder {
const static typename T::value_type value;
ValueHolder(typename T::value_type v)
{
ValueHolder::value = v;
}
}
精彩评论