当我尝试按如下方式创建模板类时:
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)'
当我在类定义中有这些特化时,所有的编译都会立即编译。所以我想我的模板语法出了问题。但很难找到具有专业化的类和功能模板的混合示例。所以我最终希望有一个对我有好心的人。
答案 0 :(得分:0)
看来你不必把“模板&lt;&gt;”高于你的专业。
如果我删除它们,一切都编译好(寻找不要在家里尝试)
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 ..
答案 1 :(得分:0)
正如您所说,您不需要模板&lt;&gt;,因为您没有专门化该功能。
你做的是功能重载!