Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用bool非类型参数实例化类模板时出错_C++_Templates - Fatal编程技术网

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

C++ 使用bool非类型参数实例化类模板时出错,c++,templates,C++,Templates,我很难弄明白为什么下面的代码(带有所示的依赖项)无法编译,如果能帮助修复它,我将不胜感激 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_SU

我很难弄明白为什么下面的代码(带有所示的依赖项)无法编译,如果能帮助修复它,我将不胜感激

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;
}
Bar.cpp

#include "Bar.h"
const bool Bar::HAS_NATIVE_SUPPORT = true;
在VisualStudio2008命令提示符中出现以下错误

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;
};

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

您需要初始化类中的静态成员,使其可用作编译时常量:

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

静态成员变量只有在类主体内部初始化时才是编译时常量

因此,要么在那里初始化它,要么使用以下变体之一:

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>();
}

静态成员变量只有在类主体内部初始化时才是编译时常量

因此,要么在那里初始化它,要么使用以下变体之一:

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>();
}