我很難弄清楚爲什麼下面這段代碼與所顯示的依賴關係不能編譯,並希望有助於幫助修復它。使用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