2011-09-01 58 views
0

我在解决嵌套部分模板特化的语法时遇到了问题。无论如何,我认为这是正确的方式。我想要的是一个返回转换值的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>)这是partialy模板:

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]); 
} 

我知道上面两个码位不工作,语法可能是太可怕了,这就是我试图找出。原谅如果这是重复的。我看了几个类似的问题,但似乎没有什么关于这个的,或者我只是没有看到它。

+0

你不能部分地专门化一个方法。尽管如此,你可以将其派发到另一个函数或类中。但代码清​​晰度在这一点上大幅下降。 –

+1

正如Tom K所说,这只是一个模板函数的例子 - 你不能*部分*专门化函数,只有类。然而,你可以完全专注于功能。 –

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