[英]Template specialization with nested unspecialized type
我在解决嵌套部分模板特化的语法时遇到麻烦。 我认为这是正确的放置方式。 我想要的是一个as()
函数,该函数返回一个强制转换值。 在大多数情况下, static_cast
可以正常工作,所以我有一个通用的版本可以做到这一点,但在某些情况下,我想具体说明。 我遇到的麻烦是尝试使用公共typename
返回两个相似的模板化类类型时。
template<typename ClassType>
class Generic
{
public:
// Constructors/etc excluded
template<typename CastType>
CastType as() const;
private:
ClassType m_value;
};
// Templated version:
template<typename ClassType> template<typename CastType> inline
CastType Generic<ClassType>::as<CastType>() const
{
return static_cast<CastType>(m_value);
}
这就是设置。 实际上,我不确定100%是否是最好的方法,但是它可以在GCC中编译并且似乎可以正常工作,所以..不管怎样。 现在,我想专门处理另一种模板化类型(在这种情况下,为Eigen::Matrix<T,4,1>
-但是也许会及时使用std::vector
或其他,即从std::vector<T>
到部分模板化的std::list<T>
):
template<> template<typename CastType> inline
CastType Generic<Eigen::Matrix<CastType,4,1> >::as<CastType>() const
{
return m_value[0];
}
这有道理吗? 如果我使用Eigen :: Matrix的大小不同并特别处理它们,那版本会有所不同吗?
template<> template<typename CastType> inline
Eigen::Matrix<CastType,3,1> Generic<Eigen::Matrix<CastType,4,1> >::as<Eigen::Matrix<CastType,3,1>() const
{
return Eigen::Matrix<CastType,3,1>( m_value[0], m_value[1], m_value[2] );
}
我知道上面的两个代码位不起作用,语法可能很糟糕,这就是我要尝试的方法。 如果这是重复的,请原谅。 我看了几个类似的问题,但似乎都没有这个问题,或者我只是没有看到。
由于不能将函数部分地专门化,因此我们将部分功能类事物专门化,而使该函数仅使用专门类。
//generic version
template<typename ClassType, typename CastType> class As {
public: CastType operator()(const ClassType& b)
{return static_cast<CastType>(b);}
};
//specialization
template<> class As<int, char* > {
public: char* operator()(const int& b)
{throw b;} //so we know it worked
};
//generic class
template<typename ClassType>
class Generic
{
public:
Generic() {m_value=0;} //codepad made me put this in
// Constructors/etc excluded
template<typename CastType>
CastType as() const; //as function
private:
ClassType m_value;
};
// as function simply grabs the right "As" class and uses that
template<typename ClassType> template<typename CastType> inline
CastType Generic<ClassType>::as() const
{
As<ClassType, CastType> impl;
return impl(m_value);
}
//main, confirming that it compiles and runs (though I didn't check b...)
int main() {
Generic<int> gint;
float b = gint.as<float>();
char* crash = gint.as<char*>();
}
代码位于: http : //codepad.org/oVgCxTMI结果:
类型为int的未捕获异常
中止了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.