簡體   English   中英

C ++在調用時指定函數的非模板版本

[英]C++ specify non-templated version of function when calling

我想知道,是否有一種方法可以強制調用非模板函數,例如:

template <class T>
void foo(T&);

void foo(const int&);

void bar()
{
   int a;
   foo(a); // templated version is called, not a usual function
}

你可以做

foo(const_cast<const int&>(a));

要么

foo(static_cast<const int&>(a));

或通過中間變量

const int& crefa = a;
foo(crefa);

或使用包裝器:

foo(std::cref(a));

或者指定foo

static_cast<void(&)(const int&)>(foo)(a);

您只需要制作一個這樣的強制轉換常量:

foo(const_cast<const int &>(a));

我想問題是您在通常的函數中使用了const 並且在模板中,它不是const T&作為參數。 這就是調用模板版本的原因。 您也可以使用將參數更改為(const int&)a而不是簡單地傳遞a

foo((const int&)a);

調用int版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM