gpt4 book ai didi

c++ - 为什么成员模板方法必须在类外使用 template<> 进行专门化

转载 作者:行者123 更新时间:2023-11-30 05:38:41 25 4
gpt4 key购买 nike

我不清楚何时以及如何template函数是由编译器创建的。所以我无法解释以下 2 个示例的行为。

示例 1。

struct C1 {                                                    
template <typename T>
void g(T t);
};

template<>
void C1::g(double x) {
cout << "Member templates. C1::g(double) " << x << endl;
}

以上代码构建并运行。但是,没有 template<> ,g++ 提示。

error: prototype for ‘void C1::g(double)’ does not match any in class ‘C1’

但是如果我将 g(double) 的定义放在类中就可以了。

问题 1:为什么成员模板方法必须在类外使用 template<> 进行专门化?

示例 2。

struct C1 {                                                          
template <typename T>
void g(T t);

void g(double x) {
cout << "C1::g(double): " << x << endl;
}
};

template<>
void C1::g(double x) {
cout << "Member templates. C1::g(double) " << x << endl;
}

C1 c;
c.g(10.5); // output: C1::g(double): 10.5

没有调用成员模板template void g()。这让我想知道

问题 2.成员模板是否专门化过?

最佳答案

The member template template void g() is not called. Which makes me wonder

这里是函数重载问题,非模板函数将在重载解决方案中赢得模板特化。

http://en.cppreference.com/w/cpp/language/overload_resolution

Best viable function

For each pair of viable function F1 and F2, the implicit conversion sequences from the i-th parameter to i-th argument are ranked to determine which one is better (except the first argument, the implicit object argument for static member functions has no effect on the ranking)

F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and

1) there is at least one argument of F1 whose implicit conversion is better than the corresponding implicit conversion for that argument of F2

2) or. if not that, (only in context of non-class initialization by conversion), the standard conversion sequence from the return type of F1 to the type being initialized is better than the standard conversion sequence from the return type of F2

3) or, if not that, F1 is a non-template function while F2 is a template specialization

4) or, if not that, F1 and F2 are both template specializations and F1 is more specialized according to the partial ordering rules for template specializations

您可以显式调用模板特化函数:

c.g<>(10.5); // output: Member templates. C1::g(double) 10.5

LIVE

关于c++ - 为什么成员模板方法必须在类外使用 template<> 进行专门化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com