Bil*_*rey 4 c++ templates specialization
我的一个类声明了一个模板化的函数:
template<class A, class B>
A do_something(const std::vector<B> &data)
Run Code Online (Sandbox Code Playgroud)
我想部分专注于typename A.B是一个实现非常小的接口的类型系列,我们使用了很多,所以我希望我的专业化是通用的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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它(使用Visual Studio 2008)时,编译器崩溃(!),我收到以下错误:
fatal error C1001: An internal error has occurred in the compiler.
Run Code Online (Sandbox Code Playgroud)
我认为这是我的问题,而不是编译器.有没有更好的方式来表达我的目标部分专业化?
通常,它是这样的:
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); }
Run Code Online (Sandbox Code Playgroud)