具有嵌套非特化类型的模板特化

Template specialization with nested unspecialized type

本文关键字:类型 嵌套 非特      更新时间:2023-10-16

我在计算嵌套部分模板专门化的语法时遇到了麻烦。我认为这是正确的说法。我想要的是一个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::矩阵,并对它们进行特殊处理,会怎么样?

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
类型异常中止。