上的模板方法专业化我有一个变体类,它使用一些函数模板专业化来获取和设置不同的类型,这些类型在Visual Studio 2010中编译和运行良好。但是,此代码位于同样需要编译的通用解决方案中在RedHat,Ubuntu的等* nix
我收到了一个错误沿着非命名空间范围显式专业化的行。我认为简单的解决方法是简单地在类的外部使用范围限定符在同一名称空间中为类定义我的特化。
但是现在我得到了实例化后发生的特化错误,因为从各种类型转换而来的类的其他方法在类中使用此模板。
那么什么是做这样的事情的正确方法:
namespace Example
{
class CSomeVariant
{
public:
bool toString(std::string& out)
{
return get(out);
}
private:
template <typename T>
bool get(T& val)
{
try {
val = boost::any_cast<T>(m_stored);
}
catch (...) {
return false;
}
return true;
}
boost::any m_stored;
};
template<>
bool CSomeVariant::get(std::string& val)
{
try {
if (m_stored.type() != typeid(std::string))
val = convertToString();
else
val = boost::any_cast<std::string>(m_stored);
}
catch(...) {
return false;
}
return true;
}
}
注:这是不实际的代码,但我相信它显示的问题。
奇怪,看起来像应该工作... – Benj
为什么你使用专业化而不是[简单重载](http://ideone.com/W1KYE)? – ildjarn
@ildjarn嗯,因为...好点。哇,我现在觉得很愚蠢。 – AJG85