【发布时间】:2015-02-18 23:49:45
【问题描述】:
我知道函数和类方法不支持部分模板特化,所以我的问题是:解决这个问题的常见解决方案或模式是什么?下面的Derived 派生自Base,并且这两个类都有虚拟方法greet() 和speak()。 Foo 持有 std::array<unique_ptr<T>, N> 并在 do_something() 中使用。 Foo 有两个模板参数:T(类类型)和N(std::array 的元素数) 如果N = 2,则存在do_something() 的高度优化版本。现在假设Foo 的T 参数并不总是基类Base。理想情况下,我想编写以下代码,但它是非法的:
//ILLEGAL
template<typename T>
void Foo<T,2>::do_something()
{
arr_[0]->greet();
}
以下是完整代码和我当前(丑陋的)解决方案。我必须对do_something() 进行两次专业化,一次用于Base,一次用于Derived。如果存在像do_something() 这样可以在特殊的N=2 情况下优化的多种方法,并且如果存在Base 的许多子类,这将变得很难看。
#include <iostream>
#include <memory>
class Base
{
public:
virtual void speak()
{
std::cout << "base is speaking" << std::endl;
}
virtual void greet()
{
std::cout << "base is greeting" << std::endl;
}
};
class Derived : public Base
{
public:
void speak()
{
std::cout << "derived is speaking" << std::endl;
}
void greet()
{
std::cout << "derived is greeting" << std::endl;
}
};
template<typename T, int N>
class Foo
{
public:
Foo(std::array<std::unique_ptr<T>, N>&& arr) :
arr_(std::move(arr))
{
}
void do_something();
std::array<std::unique_ptr<T>, N> arr_;
};
template<typename T, int N>
void Foo<T,N>::do_something()
{
arr_[0]->speak();
}
//Want to avoid "copy-and_paste" of do_something() below
template<>
void Foo<Base,2>::do_something()
{
arr_[0]->greet();
}
template<>
void Foo<Derived,2>::do_something()
{
arr_[0]->greet();
}
int main()
{
constexpr int N = 2;
std::array<std::unique_ptr<Derived>, N> arr =
{
std::unique_ptr<Derived>(new Derived),
std::unique_ptr<Derived>(new Derived)
};
Foo<Derived, N> foo(std::move(arr));
foo.do_something();
return 0;
}
【问题讨论】:
标签: c++ templates inheritance template-specialization partial-specialization