问题
How can I solve this error?
My header file
template<typename T>
class C1 {
public:
typedef std::vector<T::F> TFV;
TFV Function1();
};
My CPP file
template<typename T>
TFV C1::Function() //error: ‘TFV’ does not name a type
{ }
回答1:
First of all, use the typename
keyword to tell the compiler to interpret F
as the (qualified) name of a type:
typedef std::vector<typename T::F> TFV;
// ^^^^^^^^
Secondly, TFV
is not a type defined in the global namespace, so you have to properly qualify that as well in the definition of Function1()
:
template<typename T>
typename C1<T>::TFV C1<T>::Function1()
// ^^^^^^^^ ^^^^^^^ ^^^
{ }
Finally, the definition of member functions of a class template should be placed in a header file, unless you are providing explicit instantiations for all the template instantiations you would otherwise implicitly generate.
Failing to do so will most likely result in an unresolved references error from the linker.
回答2:
Having C++11? Then use trailing return types.
template<typename T>
class C1 {
public:
typedef std::vector<typename T::F> TFV;
TFV Function1();
};
template<typename T>
auto C1<T>::Function1() -> TFV { }
This works because after the parameters of the function, ()
in this case, the scope is the same as inside the {}
block. You have access to this
(useful in combination with decltype) and you can use TFV
without the scope resolution operator.
来源:https://stackoverflow.com/questions/15099826/typedef-with-template-parameter-in-c