从专用模板类函数调用非专用模板类函数 [英] Call non-specialised template class function from specialized template class function
问题描述
是否可以从专用模板类调用在非专用模板类中定义的函数?这是我正在尝试的示例:
Is it possible to call a function defined in a non-specialised template class from a specialised template class? Here is an example of what i am attempting:
template <typename T>
struct Convert
{
static inline void toString(unsigned num, unsigned places, std::string& str) { ... }
};
template <>
struct Convert<int8_t>
{
static inline void toString(unsigned num, std::string& str)
{
Convert<int8_t>::toString(num, digitis(num), str);
}
};
GCC 抱怨它看不到非专业化的类函数;即我猜它只在专门的类中查找.
GCC complains that it can't see the non-specialised class function; i.e. I guess it only looks within the specialised class.
有什么想法吗?
编辑
这是我的代码中更具体的示例(带有可能的解决方案):
Here is a more concrete example from my code (with a possible solution):
struct NonSpecial { };
template <typename T>
class Convert
{
template <typename R>
static inline R fromString(const register char *str, const unsigned str_len)
{
R result = 0;
//convert str to R
return result;
}
friend class Convert<int8_t>;
friend class Convert<uint8_t>;
}
template <>
struct Convert<int8_t>
{
static inline int8_t fromString(const register char* str, const unsigned str_len = 4)
{
Convert<NonSpecial>::fromString<int8_t>(str, str_len);
}
};
template <>
struct Convert<uint8_t>
{
static inline uint8_t fromString(const register char* str, const unsigned str_len = 3)
{
Convert<NonSpecial>::fromString<uint8_t>(str, str_len);
}
};
我还有其他函数 - toString()、countDigits() 等.我选择了这种方法,因此我可以为每种类型保留相同的函数名称(即不需要 toStringU32()、toString32 等).我考虑过模板专业化,但我认为这是不可能的.
I have other functions - toString(), countDigits(), etc. I have chosen this approach so I can keep the same function names for each type (i.e. don't need toStringU32(), toString32, etc.). I considered template specialization but I don't believe this is possible.
推荐答案
一般来说,这是不可能的.
In general, this isn’t possible.
有不同的可能解决方案,但它们作弊".第一个是将实际的默认逻辑提升到一个非专门的不同功能中.现在您可以从两个 toString
实现中调用此函数.
There are different possible solutions but they "cheat". The first is to hoist off the actual default logic into a different function that is not specialized. Now you can call this function from both toString
implementations.
第二种选择需要从非特化类继承并传递一个特殊标签作为模板参数:
The second alternative entails inheriting from the non-specialized class and passing a special tag as the template argument:
struct BaseClassTag { };
template <>
struct Convert<int8_t> : public Convert<BaseClassTag>
{
typedef Convert<BaseClassTag> TBase;
static inline void toString(unsigned num, std::string& str)
{
TBase::toString(num, digitis(num), str);
}
};
这篇关于从专用模板类函数调用非专用模板类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!