c++ - 模板化静态模板成员

标签 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 'const int FooTemplate::RESULT': redefinition

C3860 template argument list following class template name must list parameters in the order used in template parameter list

最佳答案

您可以尝试如下简化代码:

#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

关于c++ - 模板化静态模板成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160962/

相关文章:

c++ - 更改构造函数优先级

c++ - 为什么编译器在下面的例子中没有选择我的函数模板重载?

C 全局变量值不保存在函数之外

c++ - 为什么包含 windows.h 时 std::min 失败?

c++ - 非依赖名称场景中模板基类的名称查找

c++ - 如何处理已发布的抽象基类的变化?

c++ - 有没有办法传递函数模板作为另一个函数中的参数?

java - 静态初始化程序是否必须按分层顺序执行?

django - Heroku - 在 Django 应用程序中处理静态文件

c++ - UAC,需要管理员和文件访问