我已经看过一些类似的问题,但我仍然很困惑。我正在想办法明确地(不是通过编译器优化等)和 C++03 兼容,避免在将对象传递给对象时复制对象专门模板功能。这是我的测试代码:
#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)来避免这种情况,但这根本不起作用(显然原因在这个问题 https://stackoverflow.com/questions/4677592/specializing-function-template-for-reference-types).
好吧,我可以“通过指针传递”,但这有点丑陋。那么有没有一些技巧可以很好地做到这一点呢?
编辑:哦,可能我不清楚。我已经有一个模板化函数
template<class T> void f(T) {...}
但现在我想专门化这个函数来接受另一个对象的常量:
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 http://www.gotw.ca/publications/mill17.htm