gcc C++文件中模板特化

gr8qqesn  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(163)

我有以下代码

  1. // Foo.h
  2. class A
  3. {
  4. public:
  5. template<typename T>
  6. void doSomething(const T& myT);
  7. };
  8. extern template void A::doSomething<double>(const double& myDouble);
  9. extern template void A::doSomething<int>(const int& myDouble);
  10. template <typename T>
  11. void A::doSomething(const T& myT)
  12. {
  13. static_assert(/* properties of T */);
  14. throw std::exception();
  15. }

字符串
我想在.cpp文件中定义专门化

  1. template <>
  2. void A::doSomething<double>(const double&)
  3. {
  4. // ...
  5. }
  6. template <>
  7. void A::doSomething<int>(const int&)
  8. {
  9. // ...
  10. }


在msvc C++17上编译得很好,但在gcc 11.2.1上无法编译。
错误消息为:

  1. error: specialization of 'void A::doSomething(const T&) [with T = double]' after instantiation


问题本质上是-如何在.cpp文件中专门化模板?

ia2d9nvy

ia2d9nvy1#

您可以在头文件中声明模板专门化:

  1. #pragma once
  2. #include <exception>
  3. class A {
  4. public:
  5. template<typename T>
  6. void doSomething(const T& myT);
  7. };
  8. template<> void A::doSomething<double>(const double& myDouble);
  9. template<> void A::doSomething<int>(const int& myDouble);
  10. template<typename T>
  11. void A::doSomething(const T& myT) {
  12. throw std::exception();
  13. }

字符串
这允许您将专门化的实现保存在.cpp文件中。
旁注:与其在主函数模板中无条件地抛出异常,不如直接删除该实现,以便在有人试图使用它时得到一个链接错误。这也意味着您可以删除专门化的声明:

  1. #pragma once
  2. class A {
  3. public:
  4. template<typename T>
  5. void doSomething(const T& myT);
  6. };

展开查看全部

相关问题