保持未定义:
template <class T>
void sendit(char *buffer, unsigned len);
// C++11
template <class T>
void sendit(char *buffer, unsigned len) = delete;
使用= delete
是 IMO 的首选方法。
或者,做某种类型的静态断言(在 C++03 中使用 Boost):
template <class T>
void sendit(char *buffer, unsigned len) {
static_assert(sizeof(T) == 0, "must specialize"); // must use sizeof to make it dependant on T
}
无论如何,你确定你真的需要这里的类型模板吗?我并不是说你不应该,只是要知道有一些涉及重载的替代方案,例如:
// This is only if you're using the types as tags
// Don't do this otherwise!!!
void sendit(first_valid, char *buffer, unsigned len)
{
// this is OK
}
void sendit(second_valid, char *buffer, unsigned len)
{
// this is OK
}
sendit(first_valid(), ...); // call first
sendit(second_valid(), ...); // call second
或者使用枚举而不是类型作为模板参数:
enum foo { first, second }
template <foo Foo>
void sendit(char *buffer, unsigned len);
void sendit<first>(char *buffer, unsigned len)
{
// this is OK
}