【发布时间】:2011-02-02 15:04:53
【问题描述】:
我已经查看了一些类似的问题,但我仍然感到困惑。我试图弄清楚如何显式(而不是通过编译器优化等)和C++03兼容避免在将对象传递给specialized模板时复制它功能。这是我的测试代码:
#include <iostream>
using namespace std;
struct C
{
C() { cout << "C()" << endl; }
C(const C&) { cout << "C(C)" << endl; }
~C() { cout << "~C()" << endl; }
};
template<class T> void f(T) { cout << "f<T>" << endl; }
// This shows two possible ways, I don't need two overloads
// If I do it like (2) the function is not called, only if I do it like (1)
template<> void f(C c) { cout << "f<C>" << endl; } // (1)
template<> void f(const C& c) { cout << "f<C&>" << endl; } // (2)
int main()
{
C c;
f(c);
return 0;
}
(1) 接受C 类型的对象,并进行复制。这是输出:
C()
C(C)
f<C>
~C()
~C()
所以我尝试专门使用 const C& 参数 (2) 来避免这种情况,但这根本不起作用(显然原因在 this question 中有解释)。
好吧,我可以“通过指针”,但这有点难看。那么是否有一些技巧可以很好地做到这一点?
编辑:哦,可能我不清楚。我已经有一个模板函数
template<class T> void f(T) {...}
但是现在我想专门化这个函数来接受一个 const& 到另一个对象:
template<> void f(const SpecificObject&) {...}
但只有当我将其定义为时才会调用它
template<> void f(SpecificObject) {...}
基本上我想用这个专业化做的是使SpecificObject适应模板界面,比如
template<> void f(SpecificObject obj){ f(obj.Adapted()); } // call the templated version
EDIT2:好的,我可以强制以这种方式调用 const C& 专业化:
f<const C&>(c);
但是有没有办法让它像 f(c) 这样工作?
EDIT3:如果有人最终会有类似的问题,我终于在另一个问题中找到了这个链接,它很有帮助:http://www.gotw.ca/publications/mill17.htm
【问题讨论】:
-
而且我找不到定义这两个专业化的原因,为什么必须区分 const 引用和复制。而且我认为没有办法区分它们。
-
@mattia.penati:这不是我的本意,实际上......
-
好的,现在很清楚了。首先,如果要防止函数调用中的隐式复制,可以将
explicit放在复制构造函数的前面。现在您可以将函数f定义为template <class T> f(T const &)。否则使用重载。没有别的办法。 -
@mattia.penati:我不想改变原来的模板化函数,只是为了让传递引用与专门的函数一起工作......
-
使用重载。否则别无他法。
标签: c++ templates template-specialization