【问题标题】:Thinking in C++ template specialization思考 C++ 模板专业化
【发布时间】:2011-12-11 00:29:50
【问题描述】:

环境:Microsoft Visual Studio 2010

编码标准:C++0x 兼容

我有一个类模板

template <typename T1, int I>
class A
{
    public template <typename T2> void f(T2 x);
    /*...*/
};

template <typename T1, int I>
template <typename T2>
void A<T1, I>::f(T2 x)
{
    /*...*/
}

上述类的部分特化

template <int I>
class A<char, I>
{
    public template <typename T2> void f(T2 x);
    /*...*/
};

那么我可以像下面这样在部分特化的类中特化成员函数吗?

template <int I>
template <>
void A<char, I>::f<double>(double x)
{
}

谢谢!

注意:我不是在研究它,而是在思考它是否适用。如果您了解规则,则可以轻松评分。

【问题讨论】:

  • public void?你真的尝试编译这个吗?
  • @Pubby 谢谢。对我的问题有什么建设性的想法吗?
  • 你仍然没有尝试编译...提示 C++ 在可访问性规范方面不是 C#。
  • 出于某种原因,我记得这不可能在课堂外。其他人可以告诉你为什么/为什么不。
  • @Xeo 嗯...那是什么?如果没有完全专门化它的类,也许就不能专门化成员函数?

标签: c++ visual-studio-2010 templates generics stl


【解决方案1】:

这是无效的,因为你不能显式地特化成员函数,除非你也给任何封闭的类模板提供固定的模板参数。

不兼容 C++11,但在 MSVC 上工作

Microsoft 编译器有一个扩展,允许在类模板中声明显式特化。尽管我从未尝试过,但它很可能会接受以下非标准代码

template <int I>
class A<char, I>
{
    public:
    template <typename T2> void f(T2 x);

    template<> void f<double>(double x) {

    }
    /*...*/
};

更新:Clang 编译并报告

// clang++ -fms-extensions main1.cpp
main1.cpp:10:21: warning: explicit specialization of 'f' within class scope is a
                 Microsoft extension [-Wmicrosoft]

  template<> void f<double>(double x) {
                  ^

兼容 C++11/C++03

这里的方式是重载而不是特化

template <int I>
class A<char, I>
{
    public:
    template <typename T2> void f(T2 x);

    void f(double x) {

    }
    /*...*/
};

【讨论】:

  • 这就是我要找的东西,谢谢 Johannes。但是,如果在此类继承的情况下应用于构造函数,则内联内容可能会出现问题,对吗?
  • 我认为内联的东西有问题(继承、循环)并且即将接受重载解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多