铸造运算符到模板参数的专业化

时间:2011-12-01 20:33:50

标签: c++

我在其他任何地方都找不到这个问题,所以我终于决定问了。 我有一个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始终会返回一个引用函数声明的错误。最常见的是:

  

错误:模板ID'运算符int&lt;&gt;'表示'bar&lt; concreteType,int&gt; :: operator int()'与任何模板声明都不匹配。

我使用这些内容:

  • 将转换运算符定义为“operator int()”
  • 使用“operator typeB()”,在原始模板中声明一行“typedef B typeB;”

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

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

1 个答案:

答案 0 :(得分: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>(); };
相关问题