部分类专业化中模板方法的专业化 [英] Specialization of template method in partial class specialization

查看:142
本文介绍了部分类专业化中模板方法的专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下代码:

#include <iostream>
#include <string>
#include <typeinfo>

// template class
template <class U, class X, class T>
class Klasa{
public:   
    template <class Z>
    void Method(){
    }
};

// partial class specialization
template <class U>
class Klasa<U, int, U>
{
public: 
    // template method
    template <class Z>
    void Method(){
    }
};

// error occurs for that!
template <class U>
template <>
void Klasa<U, int, U>::Method<int>(){
}

int main() 
{ 
    Klasa<float, int, float> object;
    object.Method<float>();
    return 0;
} 

编译错误:

error: invalid explicit specialization before ‘>’ token
error: enclosing class templates are not explicitly specialized
error: template-id ‘Method<int>’ for ‘void Klasa<U, int, U>::Method()’ does not match any template declaration

我尝试为方法做专门化

void Klasa<U, int, U>::Method<int>

,但编译器不接受它。如何写这个方法的专业化?

, however compiler doesn't accept it. How to write specialization for this method?

推荐答案

不要问我确切的报价,但根据David Vandevoorde,这不能做完了。理由是,这实质上是一个功能模板的部分专业化,没有这样的事情。不允许这种情况的一个原因是,如果有类的进一步专门化,是不是应该发生什么应该发生什么:是继承的函数专用化还是不继承?

Don't ask me for exact quotes but according to David Vandevoorde this can't be done. The rationale is that this is essentially a partial specialization of a function template and there is no such thing. One reason to disallow this is that it is unclear what should happen with this specialization if there is a further specialization of the class: is the function specialization inherited or is it not inherited?

显然,说这不能做是不是真的很多的帮助。可以做什么?一个简单的方法是将实现委托给一个重载的私有实现。一个指针参数来消除各种类型之间的歧义。我意识到,整个点可能是避免使用一个额外的参数,即使它只是内部使用。另一种可能的方法是使用完全专门化的基类:成员函数模板可以被明确专门化。

Obviously, stating that this can't be done isn't really a lot of help. What can be done instead? A simple approach would be to delegate the implementation to an overloaded private implementation which takes e.g. a pointer argument to disambiguate between the various types. I realize that the whole point probably is to avoid the use of an extra argument, even if it is only used internally. Another possible approach could be the use of fully specialized base class: member function templates of this can be explicitly specialized.

这篇关于部分类专业化中模板方法的专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆