2012-07-09 324 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>(); 
}