考慮以下模板
template <typename T, int v> void func(const T&x);
我想專門針對某個班級A。這是我的嘗試(通過參考這個):
template <int v> void func<A, v>(const A&x);
然而,這是違法的。我的問題是為什么這是非法的(它違反了哪個規則),如果這違反語法,我們還有其他方法可以專門針對它A嗎?
uj5u.com熱心網友回復:
你不能部分特化一個函式模板,但你可以多載它,如下所示。
#include <iostream>
class A
{
};
template <typename T, int v> void func(const T&x) //primary template
{
std::cout<<"primary template"<<std::endl;
}
//this is an overload and not a specialization. Also partial specialization cannot be done for function templates
template <int v> void func(const A&x)
{
std::cout<<"overload not specialization"<<std::endl;
}
int main()
{
func<int, 5>(84); //uses primary template
func<5>(A()); //uses the overloaded version
return 0;
}
uj5u.com熱心網友回復:
函式模板不能部分特化,因此出現錯誤:
<source>:8:23: error: non-class, non-variable partial specialization 'func<A, v>' is not allowed
8 | template <int v> void func<A, v>(const A&x);
| ^~~~~~~~~~
例如,您可以部分專門化一個型別operator():
template <typename T, int v>
struct func{
void operator()(const T&x);
};
struct A {};
template <int v>
struct func<A, v>{
void operator()(const A&x);
};
uj5u.com熱心網友回復:
你可以用
template <typename T, int v> void func(const T&x);
template <int v> void func(const A&x);
至于為什么,我認為主要是因為它沒有提供額外的價值
template <typename T> void func(const T&x);
template <typename T> void func(const T*x);
void func(const A&);
已經是一個有效的函式"specialization"。在標準措辭的意義上并不是真正的專業化
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/346448.html
