2017-04-25 120 views
1

我已閱讀下列問題:靜態模板函數可以通過編譯器內聯嗎?

  1. Template functors vs functions
  2. C++ Functors - and their uses
  3. 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()

+1

看看程序集,看看編譯器做了什麼。一個很好的資源是https://gcc.godbolt.org/ – NathanOliver

+0

你的代碼不能編譯的原因很多。對於它的價值,編譯器應該能夠將調用內聯到'func',但是我懷疑它只會在call_func本身被內聯時才這樣做。 [在這個簡單的代碼中,編譯器內嵌了所有內容](https://godbolt.org/g/8KmlTv)。 – Cornstalks

+1

一般來說,您無法可靠地推斷優化,請始終檢查asm。在這種情況下,FWIW Clang和GCC都將這些內聯列出,但他們可能並不總是這樣做。 – harold

回答

4

但我不能推斷會發生什麼,如果將做以下

這是不可能推斷會發生什麼,你必須要嘗試一下,看看。

內聯是一種優化,而不是語言功能。何時以及它是否發生取決於您的編譯器,版本,配置方式以及可能內置的(可能內置的)調用站點周圍的其他許多上下文。