1
我已閱讀下列問題:靜態模板函數可以通過編譯器內聯嗎?
- Template functors vs functions
- C++ Functors - and their uses
- C++ function template partial specialization?
我明白C++ functors
是良好的。但我不能推斷,如果將執行以下操作會發生什麼:
template <typename T, unsigned int state>
class Foo {
public:
static Foo_func() { /* Do something */ };
}
// Partial specialization:
// -- state == 1
template <typename T>
class Foo <T, 1> {
public:
static Foo_func() { /* Do something */ };
}
template <typename F>
void call_func(F func) {
// Do something... //
func();
// Do something... //
}
int main() {
Foo <double, /*state*/ 1> obj;
// Case 1:
call_func(obj.Foo_func);
// Case 2:
call_func(Foo<double, /*state*/ 1>::Foo_func);
}
考慮腳本編譯器將能夠爲嵌入式Foo_func()
?
看看程序集,看看編譯器做了什麼。一個很好的資源是https://gcc.godbolt.org/ – NathanOliver
你的代碼不能編譯的原因很多。對於它的價值,編譯器應該能夠將調用內聯到'func',但是我懷疑它只會在call_func本身被內聯時才這樣做。 [在這個簡單的代碼中,編譯器內嵌了所有內容](https://godbolt.org/g/8KmlTv)。 – Cornstalks
一般來說,您無法可靠地推斷優化,請始終檢查asm。在這種情況下,FWIW Clang和GCC都將這些內聯列出,但他們可能並不總是這樣做。 – harold