gpt4 book ai didi

c++ - 不为派生类型调用函数模板特化

转载 作者:行者123 更新时间:2023-11-28 07:30:56 25 4
gpt4 key购买 nike

我有一个专门用于特定类型的函数模板。在某些情况下,我无法调用专用版本。举例说明

struct Base {};
struct Derived : public Base {};


template <typename VALTYPE> void FooInternal(VALTYPE&)
{
std::cout << L"FooInternal template";
}

template<> void FooInternal(Base&)
{
std::cout << L"FooInternal SPECIAL";
}

现在,如果我构造一个“Base”或“Derived”的实例并调用“FooInternal”,一切都按我预期的那样工作

int _tmain(int argc, _TCHAR* argv[])
{
int x = 7;
FooInternal(x); // Calls FooInternal<VALTYPE>() template

Base b;
FooIntenral(b); // Calls FooInternal<Base>() specialization

Derived d;
FooInternal(d); // Calls FooInternal<Base>() specialization

return 0;
}

这个的输出是

FooInternal template
FooInternal SPECIAL
FooInternal SPECIAL

但假设我在这两者之间有一个调用 FooInternal 的中间函数模板。在这种情况下,派生类型的模板解析似乎一直失败

// Intermediate template.  Just calls FooInternal.

template<typename VALTYPE>
void Foo(VALTYPE& val)
{
FooInternal<VALTYPE>(val);
}


// Now repeat the same 3 calls and see what happens with Derived...

int _tmain(int argc, _TCHAR* argv[])
{
int x = 7;
Foo(x); // Calls FooInternal<VALTYPE>() template

Base b;
Foo(b); // Calls FooInternal<Base>() specialization

Derived d;
Foo(d); // Calls FooInternal<VALTYPE>() template!!!

return 0;
}

这个程序的输出是

FooInternal template
FooInternal SPECIAL
FooInternal template

我不明白为什么——在第 3 次调用中,“Foo”不会像直接调用时那样调用 FooInternal 的专用版本。在这种情况下,编译器不应该理解是从“Base”派生的吗?我在这里缺少什么规则?

如果重要的话,我正在使用 Microsoft Visual Studio 2012 Update 3。

-乔

最佳答案

您在第一个示例中的期望以及您的编译器显然都是错误的。输出应该是“FooInternal templateFooInternal SPECIALFooInternal template”。

函数模板特化不会对模板参数推导或重载解析做任何事情。仅当不查看它的规则恰好以完全相同的模板参数结束时才使用它。

大多数时候,当您认为需要函数模板特化时,最好重载函数(使用另一个模板或非模板)。

inline void FooInternal(Base&) 
{
std::cout << L"FooInternal SPECIAL";
}

当然,如果您指定模板参数,则永远不会调用 FooInternal,因此您需要:

// Intermediate template.  Just calls FooInternal.

template<typename VALTYPE>
void Foo(VALTYPE& val)
{
FooInternal(val);
}

这应该可以让您找到您正在寻找的东西(在所有编译器上)。

关于c++ - 不为派生类型调用函数模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17734043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com