实例化后的显式专门化 [英] Explicit specialization after instantiation

查看:149
本文介绍了实例化后的显式专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

typedef vector<int> Vec;
typedef vector<Vec> VecOfVec;

template<typename Vec>
Vec DoSomething(const Vec &v);

template<>
VecOfVec DoSomething<VecOfVec>(const VecOfVec &v)
{
    VecOfVec r;
    for(auto i = v.begin(); i != v.end(); i++)
        r.push_back(DoSomething(*i));
    return r;
}

template<>
Vec DoSomething<Vec>(const Vec &v) // Error here
{
    return v; // for the sake of the example
}

我得到以下错误: p>

I get the following error:

explicit specialization of 'DoSomething<vector<int> >' after instantiation



编译器坚持它已经实例化 DoSomething< vector< int> > ,但它不能,一个简单的程序可以证明:

at the marked line.
The compiler insists that it already instantiated DoSomething<vector<int> >, while it cannot, and a simple program can prove it:

typedef vector<int> Vec;
typedef vector<Vec> VecOfVec;

template<typename Vec>
Vec DoSomething(const Vec &v);

template<>
VecOfVec DoSomething<VecOfVec>(const VecOfVec &v)
{
    VecOfVec r;
    for(auto i = v.begin(); i != v.end(); i++)
        r.push_back(DoSomething(*i));
    return r;
}

导致未解析的外部。

为什么编译器说它已经实例化它,当它不能,甚至不?为什么编译器不把它当作未解析的符号,而链接器呢?
我知道切换方法顺序解决它,但我想知道为什么是编译器这样做。

Results in unresolved external.
Why is the compiler saying it already instantiated it when it cannot and even does not? and why doesn't the compiler treat it as unresolved symbol, while the linker does? I know switching the method order solves it, but I want to know why is the compiler doing it.

推荐答案

代码请求在 DoSomething(* i)的隐式实例化。在翻译单元中没有定义模板的事实意味着它不能实例化一个特化,因此 DoSomething(* i)产生一个未解析的符号 - )错误。为了摆脱那个错误,你必须在TU中定义模板,或者在你定义模板的TU中提供一个模板的显式实例化指令。

The code requested an implicit instantiation at DoSomething(*i). The fact that you didn't define the template in that translation unit means that it could not instantiate a specialization, hence DoSomething(*i) yields an "unresolved symbol" (linker-) error in your case. To get rid of that error, you either have to define the template in that TU, or provide an explicit instantiation directive of that template in a TU where you define the template.

代码请求用于专门化的隐式实例化的事实 DoSomething< vector< int> > ,然后才明确地提供专门化足以使程序变得不合格(无需诊断,但编译器在这里做得很好,不需要这样做)。

The mere fact that the code requested an implicit instantiation for specialization DoSomething<vector<int> > before you explicitly provided that specialization is enough for the program to become ill-formed (without a diagnostic being required though; the compiler does a good job here which it is not required to do).

正如@CharlesBailey有帮助地指出的那样,声明显式特化是完全足够的;它的定义可以在其他地方,甚至在使用TU之外。

As @CharlesBailey helpfully notes, declaring the explicit specialization is perfectly sufficient; a definition of it can be given elsewhere, even outside of the using TU.

这篇关于实例化后的显式专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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