特质实例作为不同特征的模板参数

问题描述 投票:1回答:1

我正在使用模板创建特征,该特征具有特征实例作为模板参数。代码更加复杂,但是对于这个问题,我保持代码简单。代码如下:

#include <iostream>


template<int i>
struct A
{
    static const int value = i;
};


template<typename a>
struct B
{
    static const int value = a::value;
};


int main(int argc, char *argv[]) {
  std::cout << A<3>::value << std::endl; // 3
  std::cout << B< A<3> >::value << std::endl; // 3
  return 0;
}

这有效,但是现在我想将typename更改为A<int i>,以确保仅当您将B的实例作为模板参数传递时才能调用A<int i>。如果执行此操作,则会出现以下错误:

test.cpp:11:17:错误:模板参数1无效模板 a>^test.cpp:14:30:错误:尚未声明'a'静态const int value = a :: value;^

我该怎么做?

c++ templates traits
1个回答
1
投票

我该怎么做?

使用专业化

template <typename>
struct B;

template <int I>
struct B<A<I>>
 { static const int value = A<I>::value; }; // or also value = I;
© www.soinside.com 2019 - 2024. All rights reserved.