1

我很难弄清楚为什么下面的代码以及显示的依赖项无法编译,并希望帮助解决它。

主文件

#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
4

2 回答 2

3

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

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

struct Bar
{
    static const bool HAS_NATIVE_SUPPORT = true;
};
于 2012-07-09T14:28:00.133 回答
1

A static member variable is only compile time constant if it is also initialized inside the class body.

So either initialize it there, or use one of the following variants:

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>();
}
于 2012-07-09T14:44:04.863 回答