【发布时间】:2017-03-18 12:42:48
【问题描述】:
我正在尝试获取一个用于项目(对象描述)的简单示例,并且我想避免一些额外的编码,如下所示, 所以我的代码在这里:
// My function template foo : i call foo on all my object i want to describe ...
template<class T, class = void>
void foo(T &r);
// I tried this but i the compiler never use this function ...
template<class T, typename std::enable_if<std::is_base_of<Base, T>::value>::type>
void foo(T &r)
{
std::cout << "Base or Derivated" << std::endl;
}
template<> void foo<int, void>(int &r)
{
std::cout << "int" << std::endl;
}
template<> void foo<double, void>(double &r)
{
std::cout << "double" << std::endl;
}
template<> void foo<Base, void>(Base &r)
{
std::cout << "Base" << std::endl;
}
// in other librairies we can found other specialization
template<> void foo<OtherClass, void>(OtherClass &r)
{
std::cout << "OtherClass" << std::endl;
}
和主要的:
int main()
{
int a(1);
double b(5.5);
Base c;
Derivated d;
foo(a); // OK
foo(b); // OK
foo(c); // OK
foo<Base>(d); // OK
foo(d); // Compile but erreor at linking
return 0;
}
所以事实上我有很多来自 Base 的派生类......而且我不想创建所有的专业化以及其他约束(库依赖项等......)。 我想知道有没有办法打电话:
foo(d); // decltype(d) = Derivated : public Base
而不是:
foo<Base>(d); // decltype(d) = Derivated : public Base
感谢您的帮助
【问题讨论】:
-
有什么理由不将基类的引用作为参数传递?像这样:
Base &d = Derivated();然后foo(d); -
我可以,但我看不出这样做有什么区别:foo
(d);和基础 &d = Derivated();食物);就复杂性而言~可用性
标签: c++ templates template-specialization specialization