[英]C++ specify non-templated version of function when calling
I wonder, is there a way to force calling non-template function, like: 我想知道,是否有一种方法可以强制调用非模板函数,例如:
template <class T>
void foo(T&);
void foo(const int&);
void bar()
{
int a;
foo(a); // templated version is called, not a usual function
}
You may do 你可以做
foo(const_cast<const int&>(a));
or 要么
foo(static_cast<const int&>(a));
or via intermediate variable 或通过中间变量
const int& crefa = a;
foo(crefa);
or with wrapper: 或使用包装器:
foo(std::cref(a));
or alternatively specify foo
: 或者指定
foo
:
static_cast<void(&)(const int&)>(foo)(a);
您只需要制作一个这样的强制转换常量:
foo(const_cast<const int &>(a));
I guess the problem is you have use const
in the usual function. 我想问题是您在通常的函数中使用了
const
。 And in the template it is not const T&
as parameter. 并且在模板中,它不是
const T&
作为参数。 That is why template version is called. 这就是调用模板版本的原因。 Also you can use change the parameter to
(const int&)a
instead of simply passing a
您也可以使用将参数更改为
(const int&)a
而不是简单地传递a
foo((const int&)a);
调用int版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.