2012-02-22 73 views
3

我有一個模板,它依賴於頭中的常量。是這樣的:如何聲明模板中使用的常量?

  1. 定義恆定的標頭:

    // header1.hpp 
    const int CONST_VALUE1 = 10; 
    
  2. 其中I有一個模板頭:

    // header2.hpp 
    extern const int CONST_VALUE2; 
    
    template< int N > 
    struct A 
    { 
    }; 
    struct B 
    { 
        // some member functions 
        A<CONST_VALUE2> a; 
    }; 
    
  3. 與B的定義和源極常數

    // source2.hpp 
    #include "header2.hpp" 
    // implementation of B 
    const int CONST_VALUE2 = CONST_VALUE1; 
    

這當然不起作用。錯誤是這樣的:

error: the value of 'CONST_VALUE2' is not usable in a constant expression 
note: 'CONST_VALUE2' was not initialized with a constant expression 
note: in template argument for type 'int' 

是否有解決方法?或者我必須將header1.hpp包含到header2.hpp中?

+0

它不工作,因爲CONST_VALUE2是extern? – vulkanino 2012-02-22 10:37:10

+0

@vulkanino是的,這就是編譯器說的。有沒有解決方法? – 2012-02-22 10:39:32

+0

答案在這裏:http://stackoverflow.com/questions/643763/what-are-the-requirements-for-c-template-parameters – vulkanino 2012-02-22 10:40:28

回答

1

模板需要對非類型參數進行常量表達式。對於要在常量表達式中使用的變量 a const,其編譯器必須可見其初始值 。所以你可能有 在header2.hpp中包含header1.hpp。

+1

你說*可能*。這是否意味着我不必? – 2012-02-22 10:40:25

0

header1必須對header2可見。模板類不知道如何實例化自己,除非它具有所有的定義。

0

This answer說明extern const不起作用。

不過,我想周圍的工作:

  1. 變化header2.hpp定義常量:

    const int CONST_VALUE2 = 10; 
    
  2. 變化的源文件來檢查常數:

    #include "header2.hpp" 
    // implementation of B 
    static_assert(CONST_VALUE2 == CONST_VALUE1, "check the constant!"); 
    

這樣header2.hpp就不必包含header1.hpp(只需要在源文件中)。

0

模板在編譯時進行評估,因此所有的模板參數都必須已知且在那一點上是常量。通過將變量聲明爲extern,編譯器在評估模板時不知道該值,從而給出錯誤信息。

您需要確保在編譯模板時模板參數是已知值。