2012-07-09 320 views
1

我很難弄清楚爲什麼下面這段代碼與所顯示的依賴關係不能編譯,並希望有助於幫助修復它。使用bool非類型參數實例化類模板時出錯

的main.cpp

#include <cstdlib> 
#include <iostream> 

#include "Foo.h" 
#include "Bar.h" 

int main() 
{ 
    Foo<Bar> f1;  // ERROR 
    Foo<Bar,true> f2; // works 
    return EXIT_SUCCESS; 
} 

foo.h中

template<typename T, bool S = T::HAS_NATIVE_SUPPORT> 
struct Foo 
{ 
}; 

Bar.h

struct Bar 
{ 
    static const bool HAS_NATIVE_SUPPORT; 
}; 

Bar.cpp

#include "Bar.h" 
const bool Bar::HAS_NATIVE_SUPPORT = true; 

我得到在Visual Studio以下錯誤2008命令提示

cl main.cpp Bar.cpp 
main.cpp(12) : error C2975: 'S' : invalid template argument for 'Foo', expected compile-time constant expression 
     c:\tmp\c++tests\so\Foo.h(1) : see declaration of 'S' 

在G ++(GCC)4.5.3我收到以下錯誤信息:

$ g++ main.cpp Bar.cpp 
main.cpp: In function ‘int main()’: 
main.cpp:12:9: error: ‘Bar::HAS_NATIVE_SUPPORT’ is not a valid template argument for type ‘bool’ because it is a non-constant expression 
main.cpp:12:12: error: invalid type in declaration before ‘;’ token 

回答

3

的模板參數的值已到在編譯時已知,但通過在另一個源文件中初始化成員的值,編譯器無法在需要時看到該值。

需要初始化你的靜態成員在類爲它是可用作編譯時間常數:

struct Bar 
{ 
    static const bool HAS_NATIVE_SUPPORT = true; 
}; 
1

靜態成員變量是隻編譯時間常數,如果它也是類體內初始化。

因此,要麼將其初始化那裏,或使用下列變量之一:

template <bool B> 
void Y() {} 

struct X { 
    enum { foo = true }; 
    enum : bool { bar = true }; 
    static const bool frob = true; 
    static constexpr bool frobnicate = true; 
}; 

int main() { 
    Y<X::foo>(); 
    Y<X::bar>(); 
    Y<X::frob>(); 
    Y<X::frobnicate>(); 
}