模板化静态模板成员

时间:2015-08-22 21:29:35

标签: c++ templates static

好的,我有一个带有静态成员的模板类,其值只能从其中一个模板参数派生,而不是为第二个参数枚举的每个可能值定义值是否可以使用另一个模板来定义曾经为所有可能的价值观?

或者通过以下代码更好地说明:

    enum Foo
{
    FOO,
    BAR
};

enum Bar {
    OOF,
    RAB
};

template<Foo foo, Bar bar>
class FooTemplate
{
public:
    static const int RESULT;
};


template<Foo foo, Bar bar>
const int FooTemplate<Foo::FOO, bar>::RESULT = int(bar);

template<Foo foo, Bar bar>
const int FooTemplate<Foo::BAR, bar>::RESULT = 0;

尝试编译会产生以下编译错误:

  

C2086&#39; const int FooTemplate :: RESULT&#39;:重新定义

     

C3860模板参数列表必须列出类模板名称   模板参数列表中使用的顺序中的参数

2 个答案:

答案 0 :(得分:1)

您可以尝试按以下方式简化代码:

#include <type_traits>

enum Foo {
    FOO,
    BAR
};

enum Bar {
    OOF,
    RAB
};

template<Foo /*foo*/, Bar /*bar*/>
struct FooValue;

template<Bar bar>
struct FooValue<Foo::FOO, bar>
    : std::integral_constant<int, bar> { };

template<Bar bar>
struct FooValue<Foo::BAR, bar>
    : std::integral_constant<int, 0> { };

template<Foo foo, Bar bar>
class FooTemplate
    : public FooValue<foo, bar>
{
};

Demo

答案 1 :(得分:0)

不太确定你想要什么,因为这个例子看起来过于简单,但至少就例子来说,你可以这样表达:

enum Foo
{
    foo,
    bar
};

enum Bar {
    oof,
    rab
};

template<Foo foo, Bar bar>
class FooTemplate
{
public:
    static const int result = (foo == Foo::foo? int(bar) : 0);
};

template<Foo f, Bar b>
const int FooTemplate<f, b>::result;

#include <iostream>
using namespace std;
auto main() -> int
{
    cout << FooTemplate<foo, oof>::result << endl;
    cout << FooTemplate<foo, rab>::result << endl;
    cout << FooTemplate<bar, oof>::result << endl;
    cout << FooTemplate<bar, rab>::result << endl;
}
相关问题