【问题标题】:Specialization of templated member function in templated class模板化类中模板化成员函数的特化
【发布时间】:2011-07-21 08:35:42
【问题描述】:

我有一个带有模板化成员函数的模板化类

template<class T>
class A {
public:
    template<class CT>
    CT function();
};

现在我想以两种方式专门化模板化成员函数。首先与类具有相同的类型:

template<class T>
template<>  // Line gcc gives an error for, see below
T A<T>::function<T>() {
    return (T)0.0;
}

bool 类型的第二个:

template<class T>
template<>
bool A<T>::function<bool>() {
    return false;
}

这是我尝试测试的方法:

int main() {
    A<double> a;
    bool b = a.function<bool>();
    double d = a.function<double>();
}

现在 gcc 给了我上面标记的行:

error: invalid explicit specialization before ‘>’ token
error: enclosing class templates are not explicitly specialize

所以 gcc 告诉我,如果我想专门化函数,我必须专门化 A,对吗? 我不想那样做,我希望外部类的类型是开放的...

最后的答案是:不可能吗?或者有什么办法?

【问题讨论】:

标签: c++ template-specialization


【解决方案1】:

是的,这就是问题所在:

error: enclosing class templates are not explicitly specialized 

如果不专门化类,就无法专门化成员。

可以做的是将function 中的代码放在一个单独的类中并对其进行专门化,就像 basic_string 依赖于一个单独的 char_traits 类一样。然后非专业化的function 可以调用traits 类中的帮助器。

【讨论】:

    【解决方案2】:

    如果你改变实现,你可以使用重载。

    template <typename T>
    class Foo
    {
    public:
      template <typename CT>
      CT function() { return helper((CT*)0); }
    
    private:
      template <typename CT>
      CT helper(CT*);
    
      T helper(T*) { return (T)0.0; }
    
      bool helper(bool*) { return false; }
    };
    

    简单易行:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多