C++分解临时方法的特殊化模板类,是可能的

C++ factoring tempate methods specialization of a template class, is that possible?

本文关键字:特殊化 分解 方法 C++      更新时间:2023-10-16

我在一个模板类中有一个模板方法
我以前读到一个方法如果不专门化类就不能专门化
但我想将其中一些方法分解,这可能吗?

示例:

class One {
public:
  static const int number = 1;
};
class Two {
public:
  static const int number = 2;
};    
template<typename num> class A  {
private:
  num n;
public:
  template<typename type>
  void multiplyBy(); // by 1 if <int> or 1,5 if <float>
}; // A
template<> template<> void A<One>::multiplyBy<int>() {
  std::cout << 1.0*n.number << std::endl;
}
template<> template<> void A<One>::multiplyBy<float>() {
  std::cout << 1.5*n.number << std::endl;
}
template<> template<> void A<Two>::multiplyBy<int>() {
  std::cout << 1.0*n.number << std::endl;
}
template<> template<> void A<Two>::multiplyBy<float>() {
  std::cout << 1.5*n.number << std::endl;
}
int main() {
  A<One> aOne;
  A<Two> aTwo;
  aOne.multiplyBy<int>();   // 1
  aOne.multiplyBy<float>(); // 1.5
  aTwo.multiplyBy<int>();   // 2
  aTwo.multiplyBy<float>(); // 3
  return 0;
}

一个与stackoverflow相关的问题:模板类中模板函数的C++专业化
特别是这个注释:模板类中模板函数的C++专业化

我有没有办法对multiplyBy进行因式分解,一个用于int,另一个用于float
由于英语不是我的母语,也许我错过了一些简单的东西,也许是一种部分专业化的变通方法。

编辑:把A::n放在私人里,以更好地匹配我的问题。

您可以使用标签调度:

#include <iostream>
class One {
public:
  static const int number = 1;
};
class Two {
public:
  static const int number = 2;
};
template<typename num>
class A  {
    public:
    num n;
    private:
    template<typename> struct Tag {};
    void multiplyBy(Tag<int>) {
        std::cout << 1.0*n.number << std::endl;
    }
    void multiplyBy(Tag<float>) {
        std::cout << 1.5*n.number << std::endl;
    }
    public:
    template<typename type>
    void multiplyBy() {
        multiplyBy(Tag<type>());
    }
};

int main() {
  A<One> aOne;
  A<Two> aTwo;
  aOne.multiplyBy<int>();   // 1
  aOne.multiplyBy<float>(); // 1.5
  aTwo.multiplyBy<int>();   // 2
  aTwo.multiplyBy<float>(); // 3
  return 0;
}

但我想将其中一些方法分解,这可能吗?

你可能知道你不能使用:

template<> template<> void A<One>::multiplyBy<int>() {
  std::cout << 1.0*n.number << std::endl;
}

而不专门化CCD_ 1。

你可以做一些类似的事情:

#include <iostream>
class One {
public:
  static const int number = 1;
};
class Two {
public:
  static const int number = 2;
};    
template<typename num, typename type = int> struct MultiplyBy {
   static void doit(num n)
   {
      std::cout << 1.0*n.number << std::endl;
   }
};
template<typename num> struct MultiplyBy<num, float> {
   static void doit(num n)
   {
      std::cout << 1.5*n.number << std::endl;
   }
};
template<typename num> class A  {
public:
  num n;
  template<typename type>
  void multiplyBy()
  {
     MultiplyBy<num, type>::doit(n);
  }
};

int main() {
  A<One> aOne;
  A<Two> aTwo;
  aOne.multiplyBy<int>();   // 1
  aOne.multiplyBy<float>(); // 1.5
  aTwo.multiplyBy<int>();   // 2
  aTwo.multiplyBy<float>(); // 3
  return 0;
}