运算符的部分特化() [英] Partial Specialization of Operator()

查看:181
本文介绍了运算符的部分特化()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One of my classes declares a templated function:

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

喜欢部分专注于 typename A B 是一个类型的家族,实现一个漂亮的最小接口,我们使用了很多,所以我想我的专业化是通用的 B 。我怀疑这是非常烦恼,因为 typename A 只用作返回类型。

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

我发现我不能部分专门化一个函数,所以我创建了一个类如下:

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

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),编译器崩溃(!),并得到以下错误:

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

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

我假设这是我的问题,而不是编译器。

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

推荐答案

通常情况下,它是这样的:

Usually, it goes like this:

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); }

这篇关于运算符的部分特化()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆