[英]How to use Nested static templated structs in c++17
我想要实现的是使用一个结构作为另一个结构的模板参数,而不需要实例化,这样这一切都发生在编译时。 例如:
template<int v>
struct Container {
static const int value = v;
};
template<Container a, Container b>
struct BiggerContainer {
static const int value = a.v > b.v ? a.v : b.v;
};
int main() {
std::cout << BiggerContainer<Container<42>, Container<42>>::value << std::endl;
return 0;
}
我使用此代码得到的错误如下:
./code.cpp: In function 'int main()':
./code.cpp:44:61: error: type/value mismatch at argument 1 in template parameter list for 'template<Container<...auto...> a, Container<...auto...> b> struct BiggerContainer'
44 | std::cout << BiggerContainer<Container<42>, Container<42>>::value << std::endl;
| ^~
./code.cpp:44:61: note: expected a constant of type 'Container<...auto...>', got 'Container<42>'
./code.cpp:44:61: error: type/value mismatch at argument 2 in template parameter list for 'template<Container<...auto...> a, Container<...auto...> b> struct BiggerContainer'
./code.cpp:44:61: note: expected a constant of type 'Container<...auto...>', got 'Container<42>'
我在这里做错了什么? 这个错误到底是什么意思我可以改变什么来得到我正在尝试的东西?
谢谢!
你可能有:
template <int v>
struct Container {
static const int value = v;
};
// template <int v> using Container = std::integral_constant<int, v>;
template <typename lhs, typename rhs>
struct Max
{
static const int value = lhs::value > rhs::value ? lhs::value : rhs::value;
};
int main() {
std::cout << Max<Container<42>, Container<42>>::value << std::endl;
}
在 C++17 中,您不能使用 class 或 struct 作为非类型模板参数。 非类型参数必须是整数、指针、枚举或引用。 这在 C++20 中发生了变化。
具体来说,以下声明将BiggerContainer
参数化为结构的值,这是不可能的。
template<Container a, Container b>
struct BiggerContainer
代码还有一些其他问题,但这是导致您不得不重新设计的主要问题。
问题是在 BiggerContainer 的模板BiggerContainer
中,您需要为Container
指定模板 arguments ( template<Container, Container>
没有用于Container
的模板 arguments )。
一种替代方法是使用模板 function,如下所示:
template<int v1, int v2>
int BiggerContainer(Container<v1> a, Container<v2> b)
{
return a.value > b.value ? a.value : b.value;
}
然后像这样调用它:
BiggerContainer(Container<42>(), Container<42>()); // No need to add '::value'
注意:必须调用构造函数Container<val>()
而不仅仅是Container<val>
类型。 (因为我们传递的是一个值,而不是一个类型)
该解决方案的问题在于它返回一个 int (值类型),而不是Container
,但对于某些用途来说可能没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.