简体   繁体   English

在c ++模板中声明的访问常量

[英]access constant declared in a c++ template

I have 我有

template <typename A,
          typename B,
          typename C>
class Template
{
public:
    static const size_t ZONE_X = 0;
    static const size_t ZONE_Y = 1;
...
}

What is the most elegant way I to access the static const variables from other templates that in my case are dependency injection or policy to this one? 从其他模板访问静态const变量的最优雅方式是什么(在我的情况下,该模板是对此的依赖项注入或策略)? ... or I should just define the constants out of the template? ...或者我应该只从模板中定义常量?

You can use 您可以使用

Template<void,void,void>::ZONE_X

Note that, the three void s are needed for Template given its definition. 注意,给定Template的定义,需要三个void Of course, you can use other types, eg int or mixed of them: 当然,您可以使用其他类型,例如int或它们的混合类型:

Template<int,int,int>::ZONE_X

or 要么

Template<void,int,float>::ZONE_X

the argument list part should be taken with to refer the static member maybe you should not defined it in a template 参数列表部分应用于引用静态成员,也许您不应该在模板中定义它

#include <iostream>

using namespace std;
   template <typename A,
          typename B,
          typename C>
class Template
{
public:
    static const size_t ZONE_X = 0;
    static const size_t JOIN_Y = 1;

};

template<typename A>
class Template2
{
    public:
    static size_t get_zone_x()
    {
        return Template<A,A,A>::ZONE_X;
    }
};

int main()
{
   std::cout << Template<int,int,int>::ZONE_X << std::endl;
   std::cout << Template2<int>::get_zone_x() << std::endl;
   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM