【问题标题】:specialization of static method template in class template类模板中静态方法模板的特化
【发布时间】:2012-01-27 12:47:21
【问题描述】:

有没有办法让这段代码工作?

template<typename T> class test{
public:
    template<typename T2> static void f(){
        cout<<"generic"<<endl;
    }
    template<> static void f<void>(){    //specialization of static method for template T2, within generic class template with argument T
        cout<<"void"<<endl;
    }
};

如果不是,是不是因为它算作函数的部分模板特化?

【问题讨论】:

标签: c++ templates


【解决方案1】:

正如其他人在 cmets 和链接中指出的那样,当前的 C++ 模板语法没有提供简单的方法来支持这种用法。但是,如果您真的想这样做并且不介意引入一些复杂性,请继续阅读。

你必须处理的两个主要问题是:

  1. 函数模板不支持部分特化。
  2. 当您将其定义为类范围的一部分时,部分特化不起作用。

要绕过它们并接近您正在寻找的东西,您可以尝试以下方法。

  • 将模板定义移到类之外。
  • 将这些模板定义为类函子,以允许部分规范。

template<typename T>
class test
{
public:
  template <typename T2>
  static void f();
};

template <typename T1, typename T2>
struct f
{
    void operator ()(void) { cout << "generic" << endl; }
};

template <typename T1>
struct f<T1, void>
{
    void operator ()(void) { cout << "void" << endl; }
};

template <typename T>
  template <typename T2>
  void test<T>::f()
  {
    ::f<T, T2>()();
  }

int main()
{
  test<int>::f<int>();      // prints 'generic'
  test<int>::f<void>();     // prints 'void'
}

为这样的事情引入了大量额外的代码,但我想如果你想做得足够糟糕,这是有可能的。

【讨论】:

  • 我想我会在帮助类中使用静态成员,而不是实例化仿函数,但这是正确的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多