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

时间:2011-09-01 18:34:35

标签: c++ template-specialization partial-specialization

我在编写嵌套的部分模板特化的语法时遇到了麻烦。无论如何,我认为这是正确的方式。我想要的是一个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);
}

这就是设置。实际上我不是百分之百确定这是否是最好的方法,但它在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] );
}

我知道上面两个代码位不起作用,语法可能很糟糕,这就是我想要解决的问题。如果这是重复,请原谅。我看了几个类似的问题,但似乎没有关于这个,或者我只是没有看到它。

1 个答案:

答案 0 :(得分:0)

由于函数不能部分特化,我们部分地专门化了一个functionoid-thingy,并使函数只使用专门的类。

//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的未捕获异常   中止。