c++ - 使用 bool 非类型参数实例化类模板时出错

标签 c++ templates

我很难弄清楚为什么以下代码(显示了依赖项)无法编译,希望能帮助修复它。

主要.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
{
};

酒吧.h

struct Bar
{
    static const bool HAS_NATIVE_SUPPORT;
};

酒吧.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

最佳答案

模板参数的值必须在编译时知道,但是通过在另一个源文件中初始化成员的值,编译器在需要时无法看到该值是什么。

您需要在类中初始化您的静态成员,以便它可以用作编译时常量:

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

关于c++ - 使用 bool 非类型参数实例化类模板时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11397029/

相关文章:

c++ - int(int)& 或 int(int) const & 是什么类型?

templates - 在 Backbone.js 中填充嵌套下划线模板

c++ - 如何在 C++ 中使用带有模板的类型作为模板参数

C++ 通过引用传递 : error: no matching function for call

c++ - 编译C++,组织包含文件

c++ - 如何在不复制的情况下在唯一 vector 中传输小 vector 的集合

c++ - 为什么程序因错误 exc_bad_access code=exc_i386_gpflt 而中断

c++ - 绕过自动生成的赋值运算符(VS bug?)

c++ - 具有默认值的模板函数

javascript - 如何使用 Handlebars 迭代对象?