2011-12-01 66 views
2

我找不到在其他地方回答的这个问题,所以我最终决定问。 我有一个C++模板类,包括铸造操作者的一个参数的类型:铸造操作者对模板参数的专门化

template <class E, class B> 
class bar { 
    private: 
     B innerVal_; 
    [...] 
    public: 
     /* Casting to the type of the 2nd template argument */ 
     operator B() const { return innerVal_; }; // default implementation provided 
}; 

不过,我需要为某些特定的模板参数提供这种转换操作符的专业化,比如:

template<> 
bar<concreteType,int>::operator int() // <-- whoops, error! 
{ [...] } 

问题是,无论我如何指定铸造操作符的语法,gcc始终返回一个引用该函数声明的错误。最常见的一种是:

error: template-id ‘operator int<>’ for ‘bar< concreteType, int>::operator int()’ does not match any template declaration.

我与这些线路有:

  • 定义转换操作符为 “操作INT()”
  • 使用 “运营商的TypeB()”,之后宣布在原始模板中一行“typedef B typeB;”

我也玩过“typename”关键字,模板括号,并做了一些其他绝望的尝试。所有这些都会导致奇怪的错误 - 我甚至不会在这里粘贴。

我失去了一些明显的细节?你有任何提示/指针吗?任何帮助都是有用的。

回答

3

在C++中,您不能在类的模板参数上专门化成员函数。因此,这里的解决办法:

template <class E, class B> 
class bar_base { //base class with 99% of the implementation 
    private: 
     B innerVal_; 
    public: 
    [...] //most of your members here 
}; 
template <class E, class B> 
class bar : public bar_base<E,B> { //normal instantiation 
public: 
    [...] //constructors only 
    /* Casting to the type of the 2nd template argument */ 
    operator B() const { return innerVal_; }; // default implementation provided 
}; 
template <class E> 
class bar<E,int> : public bar_base<E,int> { //E,int specialization 
public: 
    [...] //constructors only 
    operator int() const { [...]}; 
}; 

,或者更简单,现在,我认为它:

private: 
    template<class T> 
    T convert_to() {return innerVal_; } 
    template<> 
    int convert_to<int>() {return innerVal_; } 
public: 
    operator B() const { return convert_to<B>(); }; 
+0

埃姆...谢谢大家的响应速度快,但我真的不undersand你的答案。 “部分特化”究竟意味着什么?据我所知,我的专业化已满: 模板<> // < - 没有参数,完全专业 酒吧 ::运营商type2(){...} (我已经更改类型为type1, type2,它们被认为是真实的类型:假设type1 = type2 = int)。 另一方面,是不是有没有涉及继承的解决方案?谢谢。 – dunadar

+0

@dunadar:无法在类的模板参数上专门化成员函数。你必须使用继承,或者对SFINAE很狡猾(我不这么认为,另外,我不确定你是否可以轻松地转换SFINAE操作符,我会考虑它) –

+0

@dunadar:我明白了我的意思你所要做的就是将这个函数变成一个_template_函数,并且一切都很好,很棒。答案已更新。 –