我的一个类声明了一个模板函数:
template<class A, class B>
A do_something(const std::vector<B> &data)
我想部分专注于 typename A
。 B
是一个类型家族,实现了一个非常小的接口(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/