简体   繁体   English

为什么显式模板实例化不起作用

[英]Why the explicit template instantiation doesn't work

Could you please explain, why the explicit template instantiation doesn't work here? 您能否解释一下,为什么显式模板实例化在这里不起作用?

template <typename T>
bool IsEqual(T v1, T v2) {
    return v1 == v2;
}

template bool IsEqual<double>(double a, double b);

int main() {  
    int c = 4;
    double d = 4.0;
    IsEqual(c,d)
    return 0;
}

The error the code produces is: 代码产生的错误是:

note:   template argument deduction/substitution failed:
note:   deduced conflicting types for parameter 'T' ('int' and 'double')

If the function isn't a template function then everything works well. 如果该函数不是模板函数,则一切正常。 So I expect an explicit instantiation to create the same function. 因此,我希望使用显式实例化来创建相同的函数。

bool IsEqualT (double a, double b) {
    return a == b;
}

Template parameter deduction doesnt take care about explicit instantiation or overload resolution. 模板参数推导不关心显式实例化或重载解析。

You have to pass arguments of same type if you want to call IsEqual or change its declaration to 如果要调用IsEqual或将其声明更改为,则必须传递相同类型的参数。

template <typename T, typename S>
bool IsEqual(T v1, S v2) {
    return v1 == v2;
}

// ... main

int c = 4;
double d = 4.0;
printf("%s", IsEqual(c,d) == true ? "True" : "False"); // Prints true

or help compiler choose right overload by specifing T as double . 或通过将Tdouble帮助编译器选择正确的重载。

IsEqual<double>(c,d);

Manually stamping out 手动冲压

template bool IsEqual<double>(double a, double b)

Doesn't stop the compiler from doing template argument deduction in 不会阻止编译器进行模板参数推导

IsEqual(c,d)

It just tells the compiler regardless of what other functions it might stamp out, you want it to stamp out that function for double s. 它只是告诉编译器,而不管它可能删除哪些其他函数,您都希望它将该函数删除double

So, since you still go through template argument deduction, and int is not the same as double you get the compiler error. 因此,由于您仍然需要进行模板参数推导,而intdouble不相同,因此会出现编译器错误。 You will either have to cast c to a double or rewrite the function to have 2 template parameters so it can take two different types. 您将不得不将c转换为双精度型,或者将函数重写为具有2个模板参数,以便可以采用两种不同的类型。

An explicit template instantiation guarantees that the compiler produces code for a particular set of template parameters, which means it will be found if the linker needs it. 显式模板实例化可确保编译器为一组特定的模板参数生成代码,这意味着如果链接器需要它,它将被找到。

It doesn't hide other combinations of template parameters, or prevent them from being instantiated (implicitly or otherwise). 它不会隐藏模板参数的其他组合,也不会阻止实例化它们(隐式或其他方式)。

As such, explicit instantiation has no effect on template parameter deduction, and no effect on overload resolution. 这样,显式实例化对模板参数的推导不起作用,对过载解析也不起作用。 The whole family of possible instantiation are still candidates. 可能实例化的整个家族仍然是候选对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM