【发布时间】:2015-01-02 12:31:25
【问题描述】:
下面的玩具示例演示了我想要实现的目标。
#include <cstddef>
template<size_t ElementSize>
class Buffer
{
public:
char buffer[ElementSize];
};
template<typename T>
class Buffer<sizeof(T)>
{
public:
char buffer[sizeof(T)];
};
int main()
{
Buffer<4> b1; // buffer with 4 bytes
Buffer<int> b2; // buffer with space for "int"
}
这段代码显然不能编译:
$ g++ test.cpp
test.cpp:12:7: error: template argument ‘sizeof (T)’ involves template parameter(s)
class Buffer<sizeof(T)>
^
test.cpp: In function ‘int main()’:
test.cpp:22:12: error: type/value mismatch at argument 1 in template parameter list for ‘template<long unsigned int ElementSize> class Buffer’
Buffer<int> b2; // buffer with space for "int"
^
test.cpp:22:12: error: expected a constant of type ‘long unsigned int’, got ‘int’
test.cpp:22:16: error: invalid type in declaration before ‘;’ token
Buffer<int> b2; // buffer with space for "int"
有什么方法可以让我有两种特殊化的模板 - 一种使用以字节为单位的显式大小(非类型参数),另一种使用类型 T(类型参数)的大小(使用 sizeof()) ?我对不需要两个具有不同名称的单独模板或任何 #define 宏的解决方案感兴趣。
我尝试在“反向”中实现它 - 将 <typename T> 作为主要模板,使用 size_t 作为专业化模板(将 char[sizeof(T)] 或 std::aligned_storage<...>::type 传递给主要模板),但是失败了也是。
【问题讨论】:
标签: c++ templates partial-specialization