C++ 如何部分填写C++;不创建新类的模板参数
是否可以“部分”填写模板参数的参数,而不引入新类或对每个大小使用C++ 如何部分填写C++;不创建新类的模板参数,c++,arrays,templates,C++,Arrays,Templates,是否可以“部分”填写模板参数的参数,而不引入新类或对每个大小使用语句 我的代码: #include <vector> #include <array> #include <tuple> struct A { int a = 1; }; struct B { int b = 1; }; struct C { int c = 1; }; template<template<class...> class _Storage, typename.
语句
我的代码:
#include <vector>
#include <array>
#include <tuple>
struct A { int a = 1; };
struct B { int b = 1; };
struct C { int c = 1; };
template<template<class...> class _Storage, typename... _Components>
struct Foo {
using Storage = std::tuple<_Storage<_Components>...>;
Storage storage;
/* ... do stuff with storage ... */
};
int main() {
Foo<std::vector,A,B,C> fooV; // works
Foo<std::array<...,16>,A,B,C> fooA; // doesn't work
return 0;
}
不,它工作得很好:
Foo<MyArray16,A,B,C> fooA; // works
Foo-fooA;//作品
但是,我必须为我需要的每个数组大小引入新的类型,这远远不是最优的。当然,我可以用#define
和所有工具轻松做到这一点,以避免代码重复,但这仍然远远不是最佳的
有人知道一种不引入新类或不使用
语句的句法方法来实现这一点吗?旧的橡皮鸭又来了。突然我找到了答案。它仍然需要一个额外的类,但我不需要一个新的每一个大小
template<size_t N> struct MyArray {
template<typename _T>
using Type = std::array<_T, N>;
};
Foo<MyArray<16>::Type,A,B,C> fooA16; // works!
Foo<MyArray<256>::Type,A,B,C> fooA256; // works!
模板结构MyArray{
样板
使用Type=std::array;
};
Foo fooA16;//作品
Foo fooA256;//作品
这不是问题的答案,但您不应该使用以下划线开头,后跟大写字母的名称,因为这些名称是编译器保留的。前一段时间还有另一个问题,这到底是什么导致了某些编译器的编译错误哇,真的吗?我一直在做这个2005年,从来没有任何问题,但很高兴知道谢谢!
template<size_t N> struct MyArray {
template<typename _T>
using Type = std::array<_T, N>;
};
Foo<MyArray<16>::Type,A,B,C> fooA16; // works!
Foo<MyArray<256>::Type,A,B,C> fooA256; // works!