命名模板靜態方法的特定實例的正確語法是什麼?命名模板靜態類方法的特定實例的語法
以下所有attempts似乎是錯誤的:
struct S
{
template<int x> static int f() { return x; }
using g1 = f<1>;
template using g2 = f<1>;
template<> using g3 = f<1>;
};
命名模板靜態方法的特定實例的正確語法是什麼?命名模板靜態類方法的特定實例的語法
以下所有attempts似乎是錯誤的:
struct S
{
template<int x> static int f() { return x; }
using g1 = f<1>;
template using g2 = f<1>;
template<> using g3 = f<1>;
};
這works:
#include <iostream>
struct S {
template<int x> static int f() { return x; }
};
auto& g = S::f<1>;
int main() {
std::cout << g() << std::endl;
return 0;
}
使用auto&
我們命名特定的模板函數實例。
C++不喜歡有模板方法(見here)
你需要將其取出局部結構。你也想爲你的typedefs使用decltype嗎?例如
typedef decltype(f<0>) t;
using g1 = decltype(f<0>);
那些只會給你類型。可能最好直接打給他們與s ::˚F< 0>等
struct S {
template<int x> static int f() { return x; }
static int g1() { return f<1>(); }
};
注意,這裏g1
不f<1>
- &S::f<1> != &S::g1
例如。但稱它具有相同的效果。 (對於一些鏈接器,這可能不是真的; msvc鏈接器,或黃金鍊接器積極設置)
using
定義了一個別名,它沒有專門化任何東西。 using
爲類,類型等定義了別名。別名和專業化是兩個完全不同的東西。
f()
不是一類。這是一種方法。類別,各種類型和這種性質的東西可以用using
或typedef
進行別名。但不是功能或方法。
如果你想專門類方法,定義在類外的方法專業化:
template<>
int S::f<1>()
{
return 0; // Or whatever your specialization function needs to do.
}
如果你想爲一個函數的別名,這基本上是一個包裝:
int f1()
{
return f<1>();
}
因此,現在調用f1()
調用專門的方法。
如果您想要專門化和「別名」靜態類方法,那麼還有一些額外的麻煩。你不能在類中定義內聯包裝器。這是因爲專業化尚未宣佈。你必須聲明包裝器;然後定義專業化後定義它:
#include <iostream>
struct S
{
template<int x> static int f() { return x; }
static int f1();
};
template<>
int S::f<1>()
{
return 0;
}
inline int S::f1()
{
return f<1>();
}
int main()
{
std::cout << S::f<4>() << std::endl;
std::cout << S::f<1>() << std::endl;
}
inline
這實際上進入一個頭文件,以避免在鏈接時重複的符號是必要的。如果整個事情進入單個翻譯單元,則可以刪除inline
。
'使用'命名一個類型。函數不是一個類型。 'f <1>'是一個函數。你能解釋一下你想要這個命名做什麼,以及你想如何使用它?假設你有'static int f_1(){return 1; }',解釋一下你想用它來做什麼,而不是'f <1>',以及你會怎麼做。 – Yakk
@Yakk我很感興趣的不是命名類型,而是以某個名字(比如g)命名f <1>,以便以後我可以調用g()而不是f <1>,意圖爲DRY,以防萬一調用這個函數模板的特定實例。這是可能的(合理的,遵循你寫的)使用不是這個工具;我該怎麼做? – Danra
如果你想要一個*變量*,可以容納*值*'f <1>',只需使用auto:'auto g = f <1>' – Caleth