2011-10-09 70 views
0

我试图使用类型特征,如“现代C++设计”使用模板来确定一个类型是否有可变大小。例如一个字符串需要可变大小的存储,一个int具有固定大小的存储。 此代码工作在Microsoft C++,现在我移植到Mac和我得到的错误...类型特征 - 显式模板特化。在xcode上失败

什么专门的正确方法“明确的分工不是在当前范围内允许”?

template <typename T> 
class MyTypeTraits 
{ 
    template<class U> struct VariableLengthStorageTraits 
    { 
     enum { result = false }; 
    }; 
    template<> struct VariableLengthStorageTraits<std::wstring> 
    { 
     enum { result = true }; 
    }; 

public: 
    enum{ IsVariableLengthType = VariableLengthStorageTraits<T>::result }; 
}; 
+0

根据“存储”的含义,字符串也有“固定大小的存储”。 –

+0

在这种情况下,我将对象序列化到磁盘。使用整数,我只需存储4个字节。对于字符串或数组,我首先存储元素数量,然后存储实际元素。所以这段代码可以帮助我以最简洁的格式存储对象的原始字节。 – Jeff

回答

3

2003 C++标准只允许封闭类定义之外的成员模板专门化。此外,定义不清的专业化必须是封闭模板的显式完全专业化。微软C++在这方面是非标准的。解决方法是简单,只需移动内部模板了封闭的模板,因为内模板并不需要其外围类模板参数:课堂之外和.cpp文件中

template<class U> struct VariableLengthStorageTraits 
{ 
    enum { result = false }; 
}; 

template<> 
struct VariableLengthStorageTraits<std::wstring> 
{ 
    enum { result = true }; 
}; 

template <typename T> 
struct MyTypeTraits 
{ 
    enum{ IsVariableLengthType = VariableLengthStorageTraits<T>::result }; 
}; 
+0

很酷,谢谢!该编译在xcode和MS上。 – Jeff

4

您不能在外部类定义中添加嵌套类的特化。它会更简单,更可重复使用,使内部特质类一个独立的实体,但:

#include <type_traits> 

template <typename> struct has_variable_length; // intentionally undefined! 
template <> struct has_variable_length<std::wstring> : std::true_type { }; 
template <> struct has_variable_length<int>   : std::false_type { }; 
// ... 

template <typename T> struct MyTraits 
{ 
    static const bool variable_length = has_variable_length<T>::value; 
    // ... 
}; 

你可以换个人特质类为detail命名空间,如果你喜欢。

+0

谢谢你。 – Jeff