1

我有一个 Visual Studio 2008 C++03 应用程序,我在其中FooTraits向一个类提供策略Foo

struct FooTraits
{
    enum { FooVal = 1 };
};

template< typename traits >
class Foo
{
public:
    typedef typename traits::FooVal foo_val; // errors on this line

    void FooDo( UINT matrix[ foo_val ] ) { /*...*/ };
};

typedef Foo< FooTraits > Foot;

int main( int argc, char* argv[] )
{
    Foot f;
    UINT matrix[ Foot::foo_val ] = { /*...*/ };
    f.FooDo( matrix );
    return 0;
}

但是,我得到了一系列编译器错误typedef

error C2146: syntax error : missing ';' before identifier 'foo_val'
error C2838: 'FooVal' : illegal qualified name in member declaration
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

创建定义固定值的策略的正确方法是什么?

4

3 回答 3

2

FooTraits::FooVal不是类型。这是枚举的一个可能值。你不能 typedef 不是类型的东西。您需要decltype(FooTraits::FooVal), 或 为枚举命名。

于 2012-05-18T14:36:48.223 回答
1

引入的枚举值enum本身不是类型。但它enum本身就是。因此,在:

enum Dummy { FooVal = 1 };

Dummy是类型,不是FooVal。您可以typedef Dummy,即:

struct FooTraits
{
    enum Dummy { FooVal = 1 };
};

/* ... */

template< typename traits >
class Foo
{
public:
    typedef typename traits::Dummy dummy;
  };

但你不能typedef FooVal,因为它不是一种类型。尝试typedef FooVal这样做就像尝试这样做:

int foo = 42;
typedef FooBar foo;

......当然,这没有任何意义。

这是您的代码,已修复:

struct FooTraits
{
    enum { FooVal = 1 };
};

template< typename traits >
class Foo
{
public:
    void FooDo( unsigned matrix[ traits::FooVal] ) { matrix;/*...*/ };
};

typedef Foo< FooTraits > Foot;

int main(  )
{
    Foot f;
    unsigned matrix[ FooTraits::FooVal ] = { /*...*/ };
    f.FooDo( matrix );
    return 0;
}
于 2012-05-18T14:40:04.993 回答
0

你不能 typedeftraits::FooVal因为它不是类型。

使用此语法:

static const int foo_val = traits::FooVal;
于 2012-05-18T14:38:56.803 回答