当我尝试创建一个模板类时,如下所示:
template <typename TList>
class Variant
{
public :
std::string toString(); // var.toString()
template<typename T>
std::string toString(); // var.toStrint<int>();
protected:
template <typename T>
std::string toString(T v); // internal Specialization
template <>
std::string toString(int v); // internal Specialization
template <typename T>
const T & get()
{
std::size_t type_index = TypeListNamespace::IndexOf<TList, T>::value ;
if ( type_index == max_num_of_t || type_index != _type_index)
throw std::bad_cast() ;
void * ptr = (void*) &_variant_holder;
T * vptr = reinterpret_cast<T *>(ptr);
return *vptr;
}
};
// CPP FILE:
template <typename TList>
std::string Variant<TList>::toString ()
{
// var.toString()
}
template<typename TList>
template<typename T>
std::string Variant<TList>::toString ()
{
return toString( get<T>() );
}
template<typename TList>
template<typename T>
std::string Variant<TList>::toString (T v)
{
// no default toString method.
return "";
}
template<typename TList>
template<>
std::string Variant<TList>::toString (int v)
{
// Specialized toString for int values:
return Core::Utility::formatString("%i", v );
}
.. other specializations ..
我收到以下错误:
error C2244: 'Core::Variant<TList>::toString': unable to match function definition to an existing declaration
2> Definition
2> 'std::string Core::Variant<TList>::toString(int)'
2> Available Deklarations
2> 'std::string Core::Variant<TList>::toString(T)'
2> 'std::string Core::Variant<TList>::toString(void)'
2> 'std::string Core::Variant<TList>::toString(void)'
当我在类定义中立即编译了这些专业时。所以我想我在模板语法上犯了问题。但是很难找到混合使用具有专业化的类和函数模板的示例。所以我最终来到这里,希望有人能给我一个很好的提示。
似乎您不必将"模板<>"放在您的专业之上。
如果我删除它们,一切都可以正常编译(寻找不要在家里尝试这个)
template <typename TList>
class Variant
{
public :
std::string toString(); // var.toString()
template<typename T>
std::string toString(); // var.toStrint<int>();
protected:
template <typename T>
std::string toString(T v); // internal Specialization
// DON'T TRY THIS AT HOME: template <>
std::string toString(int v); // internal Specialization
template <typename T>
const T & get()
{
std::size_t type_index = TypeListNamespace::IndexOf<TList, T>::value ;
if ( type_index == max_num_of_t || type_index != _type_index)
throw std::bad_cast() ;
void * ptr = (void*) &_variant_holder;
T * vptr = reinterpret_cast<T *>(ptr);
return *vptr;
}
};
// CPP FILE:
template <typename TList>
std::string Variant<TList>::toString ()
{
// var.toString()
}
template<typename TList>
template<typename T>
std::string Variant<TList>::toString ()
{
return toString( get<T>() );
}
template<typename TList>
template<typename T>
std::string Variant<TList>::toString (T v)
{
// no default toString method.
return "";
}
template<typename TList>
// DON'T TRY THIS AT HOME: template<>
std::string Variant<TList>::toString (int v)
{
// Specialized toString for int values:
return Core::Utility::formatString("%i", v );
}
.. other specializations ..
正如你所说,你不需要模板<>,因为你没有专门化这个功能。
你所做的是函数重载!