0

我对 c++ 模板专业化有点困惑。

两者之间的确切区别是什么:

template<typename T>
T foo (T a) {
    return a;
}

template<>
char* foo<char*> (char* a) {
    return a;
}

template<typename T>
T foo (T a) {
    return a;
}

char* foo<char*> (char* a) {
    return a;
}

另外- template<> 是否定义了第二个模板?/如果是这样,那有什么用?

问候并感谢您的帮助

4

2 回答 2

2

The second one is simply invalid syntax. You cannot use a template parameter in a function declaration unless you have declared the function to be a template.

The first one declares a specialization of the function template foo. Whenever you use foo with template parameter char * the specialization is used instead of the original definition.

于 2013-11-10T22:57:22.353 回答
1

The template <> notation introduced a full specialization of a template: that is, the general version of the template is not used when the deduced template parameters are those of the full specialization. However, any deviation would still use the general template:

foo(17);      // uses your general template
foo("hello"); // also uses your general template! T is deduced as char const*
char world[] = "world";
foo(world)    // uses your specialization

In principle, this is exactly who overloading would work! Obviously, for class templates there is no overloading and you'd need to specialize them. However, even for function templates specialization is reasonable: when the template arguments are explicitly specified:

foo<char*>(world); // calls the specialization

If you use overloading instead, the overload wouldn't be used:

template <typename T>
void bar(T) { /*...*/ }

void bar(char*) { /*...*/ }

bar(world);         // calls the bar(char*) overload
bar<char*>(world);  // calls the template

With respect to your two alternatives: the second alternative isn't legal C++. The second definition looks a bit like a specialization but you need to introduce a specialization using template <>.

于 2013-11-10T22:58:35.127 回答