Mat*_*att 2 c++ templates const template-specialization
一个专门用于const char *捕获的模板char *吗?
例如:
template <typename T> class Foo { /* ... */ };
template <> class Foo<const char *> { /* ... */ };
Run Code Online (Sandbox Code Playgroud)
会Foo<char *>参考通用模板还是专用模板?
模板类和函数仅匹配精确匹配,所以在你的情况下,Foo<char*>将涉及通用的,因为char*和const char*有不同的类型.这使得函数更加混乱,因为有时会将引用添加到类型中:const char*&.
创建一个接受指针变体的类模板有点复杂,但通常或多或少地像这样工作:
template <typename T, typename allowed=void> class Foo { /* ... */ };
template <typename T>
class Foo<T, typename std::enable_if<std::is_same<T, char*>::value ||
std::is_same<T, const char*>::value
>::type> { /* ... */ };
Run Code Online (Sandbox Code Playgroud)
根据您正在做的事情,您可能也需要std::remove_reference<T>.