特征实例作为不同特征的模板参数
Trait instance as template parameter for different trait
我正在用一个模板创建一个特征,它有一个特征实例作为模板参数。代码比较复杂,但是对于这道题我保持代码简单。代码如下:
#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>
之类的内容,以确保只有在传递 A<int i>
的实例时才能调用 B
作为模板参数。
如果我这样做,我会收到以下错误:
test.cpp:11:17: error: template argument 1 is invalid
template<\A<\int i> a>
^
test.cpp:14:30: error: 'a' has not been declared
static const int value = a::value;
^
我该怎么做?
How do I do this?
使用专业化
template <typename>
struct B;
template <int I>
struct B<A<I>>
{ static const int value = A<I>::value; }; // or also value = I;
我正在用一个模板创建一个特征,它有一个特征实例作为模板参数。代码比较复杂,但是对于这道题我保持代码简单。代码如下:
#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>
之类的内容,以确保只有在传递 A<int i>
的实例时才能调用 B
作为模板参数。
如果我这样做,我会收到以下错误:
test.cpp:11:17: error: template argument 1 is invalid template<\A<\int i> a> ^ test.cpp:14:30: error: 'a' has not been declared static const int value = a::value; ^
我该怎么做?
How do I do this?
使用专业化
template <typename>
struct B;
template <int I>
struct B<A<I>>
{ static const int value = A<I>::value; }; // or also value = I;