考虑这样两个方差示例
struct A{
template<class T, int R>
friend void show();
private:
int c;
};
template<class T, int R = decltype(T{}.c){0} >
void show(){
}
int main(){
show<A>();
}
Run Code Online (Sandbox Code Playgroud)
struct A{
template<class T, int R>
friend void show();
private:
int c;
};
template<class T, int R = decltype(A{}.c){0} >
void show(){
}
int main(){
show<A>();
}
Run Code Online (Sandbox Code Playgroud)
Clang 接受#2并拒绝#1:
<source>:14:3: error: no matching function for call to 'show'
show<A>();
^~~~~~~
<source>:10:6: note: candidate template ignored: substitution …Run Code Online (Sandbox Code Playgroud) 我想让MemoryPool在运行时动态分配和取消分配内存,而无需让OS尝试加快代码执行(和学习)的速度。为了简化语法,我希望能够指定内存段的大小,作为它们包含的类型或原始大小。
为此,我想制作一个可以使用Type或size_t并继续发送sizeof Type或size的模板。
template<size_t SegmentSize>
class MemoryPool_Internal
{
public:
static const size_t Size = SegmentSize;
/*Using SegmentSize to do logic*/
};
template<size_t Size>
class MemoryPool : public MemoryPool_Internal<Size> { };
template<class Size>
class MemoryPool : public MemoryPool_Internal<sizeof(Size)> { };
Run Code Online (Sandbox Code Playgroud)
我希望上面的代码片段发生的事情是
std::cout << MemoryPool<5>::Size << std::endl;
std::cout << MemoryPool<int>::Size << std::endl;
Run Code Online (Sandbox Code Playgroud)
打印5和sizeof(int)。
但是5会引发C3855,因为它不是一个类;而int会引发E0254,因为第一个模板中不允许类型。有什么办法可以在编译时解决每个目标模板的问题?