I’m having difficulty figuring out why the following bit of code, with the dependencies shown, does not compile and would appreciate help help fixing it.
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;
I get the following error in the Visual Studio 2008 Command Prompt
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'
In the g++ (GCC) 4.5.3 I get the following error message:
$ 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
The values of template parameters have to be known at compile time, but by initializing the value of the member in another source file, the compiler can’t see what the value is when it needs it.
You need to initialize your static member in the class for it to be usable as compile-time constant: