假设我有一个使用原始指针的模板:
template<typename T>
void processPointer(T* ptr);
我不希望它被void*
指针调用。看来我有两个选择。我可以删除非模板重载:
void processPointer(void*) = delete;
或者我可以删除一个模板实例化:
template<>
void processPointer<void>(void*) = delete;
声明非模板重载更容易(不使用尖括号)。我更喜欢删除模板实例化有什么原因吗?
发布于 2014-01-10 02:37:31
支持模板版本的Here's one reason:processPointer<void>(void*)
仍然可以直接调用,避免了其他重载。
发布于 2014-01-10 02:29:31
我看不出有任何理由在这里使用模板
事实上,通过删除非模板重载,您可以摆脱一些边缘情况下的模糊调用,因为非模板优先于模板实例化。从而在大多数情况下使其按所需的方式工作。
发布于 2014-01-10 02:31:34
这可能会给我们一些洞察力:
#include <iostream>
struct X
{
template<typename T>
void processPointer(T* ptr) {
std::cout << "Template\n";
}
// error: explicit specialization in non-namespace scope ‘struct X’
// template<>
// void processPointer(void*) = delete;
// Overload but no specialization
// This will prevent lookup the specialization outside the class, when no
// template argument is explicitly given. However, with an explicit
// template argument the specialization is called.
void processPointer(void*) = delete;
};
// Specialization outside the class body
template<>
void X::processPointer(void* ptr) {
std::cout << "Specialization\n";
}
int main ()
{
X x;
//error: use of deleted function ‘void X::processPointer(void*)’
//x.processPointer((void*)0);
// Explicit template argument:
x.processPointer<void>((void*)0);
}
结论:@Casey的答案成立。
https://stackoverflow.com/questions/21028144
复制相似问题