简体   繁体   English

在封闭类模板参数下初始化嵌套模板化类成员

[英]Initialization of nested templated class members under enclosing class template argument

How to get around with this?如何解决这个问题?

enum SID {SID_A, SID_B};

template<SID sid>
class Emp
{
    public:
    template<typename T> struct s{T a;};

    Emp<sid>(){
        if constexpr(sid == SID_A){
            s<T>(){a = 0;} //error: use of undeclared identifier 'T'
        }
        if constexpr(sid == SID_B){
            s<T>(){a = 1;} //error: use of undeclared identifier 'T'
        }
    }
};

Compiler: clang 9.0编译器:clang 9.0

Edit -----编辑 - - -

I would like to achieve a default initialization of struct member sa depending on the argument of sid .我想根据sid的参数实现结构成员sa的默认初始化。
T would usually be an int or float . T通常是intfloat

Eg:例如:

Emp<SID_A> emp_a; //here s.a = 0
Emp<SID_B> emp_b; //here s.a = 1

If I understand you correctly, you wish Emp have a data member, s , which is a struct containing a numerical data member, a .如果我理解正确的话,你希望Emp有一个数据成员, s ,这是一个包含数值数据成员的struct中a This member should be an int with initial value 0 if this is an Emp<SID_A> , whereas for an Emp<SID_B> , it should be a float with value 1.0.如果这是一个Emp<SID_A> ,这个成员应该是一个初始值为 0 的 int ,而对于一个Emp<SID_B> ,它应该是一个值为 1.0 的浮点数。 I am guessing you want to have the freedom to associate additional values of type SID with different numeric types and values for this->sa .我猜您想自由地将SID类型的其他值与this->sa不同数字类型和值相关联。

You can do this with template specialization.您可以使用模板专业化来做到这一点。 Declare the type of s as a struct S before the class Emp :在类Emp之前将s的类型声明为结构体S

#include <type_traits>

enum SID {SID_A, SID_B};

template <SID> struct S;
template <> struct S<SID_A> { typedef int   Number; Number a;};
template <> struct S<SID_B> { typedef float Number; Number a;};
// You can define further specializations here

template<SID sid>
class Emp
{
  public:
    S<sid> s;

    Emp()
    {
      switch(sid)
      {
        case SID_A : s.a = 0.1; break; // Note value is 0.1 to prove it's an int
        case SID_B : s.a = 1.1; break; // Note value is 1.1 to prove it's a float
        // define further cases here
        default: ;
      }
    }
};

Now:现在:

#include <iostream>

int main()
{
  Emp<SID_A> A;
  Emp<SID_B> B;
  std::cout << A.s.a << std::endl;
  std::cout << B.s.a << std::endl;
  return 0;
}

output:输出:

0
1.1

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

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