【问题标题】:Templated static template members模板化静态模板成员
【发布时间】:2015-08-22 21:29:35
【问题描述】:

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

或者用下面的代码更好地说明:

    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': 重新定义

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

【问题讨论】:

  • 只要具有与类模板相同的正式模板参数即可。
  • @Cheersandhth.-Alf 谢谢你,修复了其中一个错误,但留下一个并产生另一个错误。有什么想法吗?
  • 从第二个中删除const int
  • 只有当类模板本身存在关联的部分特化like here时,静态数据成员的部分特化才可能存在(虽然它不是部分特化,它只是一个定义)跨度>
  • @erip 这使得编译器将 FooTemplate<:bar bar>::RESULT 视为类型名???

标签: c++ templates static


【解决方案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

【讨论】:

    【解决方案2】:

    不太确定您想要什么,因为该示例似乎过于简单,但至少就示例而言,您可以这样表达:

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

    【讨论】:

    • 我已经使用了你的方法,如下所示pastebin.com/zuBWhe03,唯一的问题是当你有更大的枚举时,链式三元表达式变得有点烦人,所以如果有更好的方法会更好表达出来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2012-02-02
    相关资源
    最近更新 更多