我提供了一个支持函数 bar() 的库。当您传入标量值(例如 double、int 等)时,它所做的操作与传入非标量值(在所有预期情况下,用户定义类型)时发生的操作不同。所以我写了这样的代码:
#include <iostream>
class Foo
{
public:
template <class T> void bar(T const &rhs) { std::cout << "T" << std::endl; }
void bar(double rhs) { std::cout << "double" << std::endl; }
};
int main()
{
Foo foo;
foo.bar(4);
}
问题出在 main() 的第二行。该代码的结果是“T”的输出。编译器更喜欢模板而不是对 bar(double) 的调用,我假设这是因为参数是 int,它宁愿将其转换为 int const& (因为 const& 可以引用 r 值)。
我的问题是“有没有一种方法可以支持每个标量值而无需明确调用它们?”我真的不想列出所有可能的类型,因为……嗯……有很多。我必须涵盖从 char 到 long long 的所有内容,包括 volatile 和 unsigned 的每种组合,等等。
我知道只需将 4 更改为 4.0 即可,但这是针对库的公共(public)接口(interface),并要求用户键入 4.0
而不是 4
只是脏了。
最佳答案
是的,具有特征:
#include <type_traits>
#include <iostream>
class Foo
{
public:
template <class T>
typename std::enable_if<!std::is_scalar<T>::value, void>::type bar(T const & rhs)
{
std::cout << "T" << std::endl;
}
void bar(double rhs)
{
std::cout << "double" << std::endl;
}
};
类型有六种基本类别:标量、函数、数组、类、 union 和引用。以及void
。他们每个人都有相应的特征。 See here for more details.
关于c++ - 非内置函数的模板,内置函数的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13130604/