当我尝试按如下方式创建模板类时:
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)'
当我在类定义中拥有这些特化时,都立即编译了。所以我想我的模板语法有问题。但是很难找到混合了具有专业化的类和函数模板的示例。所以我最终来到这里希望有人对我有很好的暗示。