[英]How to do achieve “const” and “non-const” overloading without duplicated codes?
template <typename T, typename Predicate, typename Operation>
void Foo(T& entity, Predicate pred, Operation op)
{
if (pred(entity))
{
op(entity);
}
// and blah
}
template <typename T, typename Predicate, typename Operation>
void Foo(const T& entity, Predicate pred, Operation op)
{
if (pred(entity))
{
op(entity);
}
// and blah
}
PS
T& entity
+ pred(const T& entity)
+ op(const T& entity)
是可以接受的。
const T& entity
+ pred(T& entity)
+ op(T& entity)
應該引發編譯錯誤。
使用C ++ 11的解決方案是可以的。
這里的例子:
class MyEntity
{
public:
MyEntity(int e):e(e){}
int e;
};
MyEntity a = 1234;
MyEntity& ra = a;
const MyEntity& cra = a;
auto pred = [](const MyEntity& i)
{
return true;
};
auto cop = [](const MyEntity& i)
{
cout<<i.e<<endl;
};
auto op = [](MyEntity& i)
{
++i.e;
cout<<i.e<<endl;
};
Foo(ra, pred, op); // ok
Foo(ra, pred, cop); // ok
Foo(cra, pred, cop); // ok
Foo(cra, pred, op); // error
您可以使用轉發參考(也稱為“通用參考” ):
template <typename T, typename Predicate, typename Operation>
void Foo(T&& entity, Predicate pred, Operation op)
{
if (pred(entity))
{
op(std::forward<T>(entity));
}
// and blah
}
你可以只使用非const Foo
,並將const
驗證留給特定的pred
和op
。
如果pred
或op
需要非const entity
,並且entity
是const
(如示例代碼中的第4次調用),編譯器將拋出錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.