简体   繁体   English

为什么 C++ 标准不允许函数模板偏特化?

[英]Why does the C++ standard not allow function template partial specialization?

I read something that it might be confusing for the compiler to write我读了一些编译器编写可能会令人困惑的东西

template <class T>
void calculator<std::complex<T>>::myMin();

but maybe just give it a hint like so?但也许只是给它一个提示? To make it clear that it is a partial specialization.明确表示它是部分专业化。

template < , class T>
void calculator<std::complex<T>>::myMin();

Fromhttp://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#229 linked by @danh in the comments above:来自http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#229由 @danh 在上面的评论中链接:

Notes from 10/00 meeting: 10/00 会议记录:

A major concern over the idea of partial specialization of function templates is that function templates can be overloaded, unlike class templates.函数模板的部分特化思想的一个主要问题是函数模板可以被重载,这与类模板不同。 Simply naming the function template in the specialization, as is done for class specialization, is not adequate to identify the template being specialized.简单地命名特化中的函数模板,就像对类特化所做的那样,不足以识别被特化的模板。

Why does the C++ standard not allow function template partial specialization?为什么 C++ 标准不允许函数模板偏特化?

Because, reverse your thinking, what would happen if the Standard allows template function to be partially specialized?因为,反过来你的想法,如果标准允许模板函数部分特化会发生什么?

Suppose this simple example assuming the Standard allows partial specialization of template functions:假设这个简单的例子假设标准允许模板函数的部分特化:

template<class T> void f( T ) { print("A-overload") };  
template<class T> void f( T* ){ print("B-overload") };
 
// template<class T> void f(T*) { print("A-partial-specialization") };

Can you now differentiate between the B-overload and partial specialization of A?你现在能区分 A 的 B 重载和部分特化吗? Indeed you can't!确实不能!

Moreover, suppose you have another overload that takes T** and a partial specialization from overload-A or overload-B with exactly the same signature, what will you do?此外,假设您有另一个重载,它采用T**和来自重载-A 或重载-B 的部分特化,具有完全相同的签名,您会怎么做?

In general, The notion of partial specialization only exists for class templates (described by §14.5.5) and member templates (ie members of a template class that are themselves template functions, described by §14.5.5.3/2).一般来说,部分特化的概念只存在于类模板(由 §14.5.5 描述)和成员模板(即模板类的成员,它们本身就是模板函数,由 §14.5.5.3/2 描述)。 It does not exist for ordinary members of class templates, nor does it exist for function templates – simply because it is not described by the Standard.它不存在于类模板的普通成员中,也不存在于函数模板中——仅仅是因为标准没有描述它。

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

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