加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在模板类A中访问X和Y,如模板类> A类;

发布时间:2020-12-16 09:37:44 所属栏目:百科 来源:网络整理
导读:在另一个模板类中使用模板类参数的模板参数的正确语法是什么? 例如:如何在类Foo中访问类Param的X和Y? 程序: template template int,int class X1struct Foo {int foo() {printf("ok%d %dn",X1::X,X1::Y);return 0;}};template int X,int Y class Param
在另一个模板类中使用模板类参数的模板参数的正确语法是什么?

例如:如何在类Foo中访问类Param的X和Y?

程序:

template < template < int,int > class X1>
struct Foo {
int foo() {
printf("ok%d %dn",X1::X,X1::Y);
return 0;
}};

template < int X,int Y >
class Param {
int x,y;
public:
Param(){x=X; y=Y;}
void printParam(){
cout<<x<<" "<<y<<"n";
}
};

int main() {
Param<10,20> p;
p.printParam();
Foo< Param > tt;
tt.foo();
return 0;
}

对于上面的代码,对于printf语句编译抱怨:

In member function 'int Foo<X1>::foo()':
Line 4: error: 'template<int <anonymous>,int <anonymous> > class X1' used without template parameters
compilation terminated due to -Wfatal-errors.

解决方法

你不能.模板模板参数表示您在没有提供模板参数的情况下获取模板名称.

Foo< Param > tt;

在这里,您可以看到没有为Param提供任何值.您将获取模板模板参数,以便Foo本身可以使用它喜欢的任何参数来实例化Params.

例:

template < template < int,int > class X1>
struct Foo {

    X1<1,2> member;

    X1<42,100> foo();
};

template <int N,int P> struct A {};

template <int X,int Y> struct B {};

Foo<A> a_foo;  //has a member of type A<1,2>,foo returns A<42,100>
Foo<B> b_foo; //has a member of type B<1,foo returns B<42,100>

但是如果你想让你的Foo输出那些整数,它必须采用真实的类型,而不是模板.其次,模板参数(X和Y)的名称仅在它们在范围内时才有意义.否则它们完全是任意标识符.您可以使用简单的元编程来检索值:

#include <cstdio>

template <class T>
struct GetArguments;

//partial specialization to retrieve the int parameters of a T<int,int>
template <template <int,int> class T,int A,int B>
struct GetArguments<T<A,B> >
{
   enum {a = A,b = B};
};
//this specialization also illustrates another use of template template parameters:
//it is used to pick out types that are templates with two int arguments

template <class X1>
struct Foo {
  int foo() {
    printf("ok%d %dn",GetArguments<X1>::a,GetArguments<X1>::b);
    return 0;
  }
};

template < int X,int Y >
class Param {
public:
   void print();
};

//this is to illustrate X and Y are not essential part of the Param template
//in this method definition I have chosen to call them something else
template <int First,int Second> 
void Param<First,Second>::print()
{
   printf("Param<%d,%d>n",First,Second);
}

int main() {

    Foo< Param<10,20> > tt;
    tt.foo();
    Param<10,20> p;
    p.print();
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读