c++ - Operator() 的部分特化

标签 c++ templates specialization

我的一个类声明了一个模板函数:

template<class A, class B>
A do_something(const std::vector<B> &data)

我想部分专注于 typename AB 是一个类型家族,实现了一个非常小的接口(interface),我们经常使用它们,所以我希望我的特化在 B 上是通用的。我怀疑这是双重烦恼,因为 typename A 仅用作返回类型。

从互联网上,我了解到我不能部分特化一个函数,所以我创建了一个类,如下所示:

template<class A, class B> 
class do_something_implementation {
  public:
    do_something_implementation(const std::vector<B> &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector<B> data;
}

当我尝试编译它(使用 Visual Studio 2008)时,编译器崩溃 (!) 并且出现以下错误:

fatal error C1001: An internal error has occurred in the compiler.

我认为这是我的问题而不是编译器的问题。有没有更好的方式来表达我想要的部分特化?

最佳答案

通常,它是这样的:

template <typename A, typename B>
struct DoSomethingHelper
{
    static A doIt(const std::vector<B> &data);
};

template <typename B>
struct DoSomethingHelper<double, B>
{
    static double doIt(const std::vector<B> &data) { ... }
};

template <typename B>
struct DoSomethingHelper<int, B>
{
    static int doIt(const std::vector<B> &data) { ... }
};

template<class A, class B>
A do_something(const std::vector<B> &data)
{ return DoSomethingHelper<A, B>::doIt(data); }

关于c++ - Operator() 的部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4440165/

相关文章:

c++ - std::regex 在 VC2015U3 上比 boost::regex 慢得多

c++ - 将变量的引用传递给模板

c++ - 从模板切换传递的类型

c++ - 类范围内的类模板特化?

c++ - C++ 模板如何专用于所有 32 位 POD 类型?

c++ - ASIO 示例代码在应该之前关闭套接字

c++ - 计算 C 中 NSDate 之间的秒数

c++ - 在 NT 之前的系统上调用 NT 函数

c++ - 从函数模板错误返回修改后的值

c++ - C++ 中基于类型的模板函数