[英]Specialising a templated function for a templated (Armadillo) class
我试图将一个非常简单的日志记录类放在一起,该类专门处理某些类型,尤其是向量。 我希望在使用<<
运算符时具有默认行为,但是在某些情况下可以对其进行修改。 设置是:
class LoggerStream
{
template <typename ArgType>
LoggerStream & operator<< (const ArgType &arg)
{
// Standard logging logic
return *this;
}
template <typename DataType>
LoggerStream & operator<< (const std::vector<DataType> &arg)
{
// Specialised logging logic
return *this;
}
template <typename DataType>
LoggerStream & operator<< (const arma::Col<DataType> &arg)
{
// Specialised logging logic
return *this;
}
LoggerStream & operator<< (const double &arg)
{
// Specialised logging logic
return *this;
}
// Other stuff...
};
double
情况下工作正常。 问题在于,对于向量类型的子类 ,通用模板似乎优先,而更具体的模板将被忽略。
由于所有这三种模板化案例都只有一个通用模板参数,我猜矢量案例并不是最专业的,但是如果被认为是模棱两可的,我会期望编译器错误。
(它编译得很好。)那么,如何指示专门化但仍对向量元素的类型进行概括?
提前致谢。
我想这与如何实现
Col
类的一些细节有关。
我也使用(和别名)
arma::Col<T>::fixed<N>
,但是为此写一个特定的重载似乎没有帮助。
任何想法欢迎。
我无法复制。 此代码可以正常运行:
#include <iostream>
#include <vector>
using namespace std;
class LoggerStream
{
public:
template <typename ArgType>
LoggerStream &operator<< (const ArgType &arg)
{
// Standard logging logic
cout << "In general" << endl;
return *this;
}
template <typename DataType>
LoggerStream &operator<< (const std::vector<DataType> &arg)
{
// Specialised logging logic
cout << "In vector" << endl;
return *this;
}
};
int main()
{
LoggerStream foo;
vector<int> v;
foo << v; // calling the vector specialization
}
我之所以回答自己的问题,不是因为我有一个解决方案,而是要在进一步调查后弄清问题。 实际上,这似乎并不专门针对arma::Col
; 相反,当参数为子类类型时,问题似乎优先于更具体的重载。 一个不使用Armadillo即可显示问题的简单示例是
#include <iostream>
#include <vector>
using namespace std;
template <typename DataType>
class MyVector : public std::vector<DataType> {};
class LoggerStream
{
public:
template <typename ArgType>
LoggerStream &operator<< (const ArgType &arg)
{
cout << "In general" << endl;
return *this;
}
template <typename DataType>
LoggerStream &operator<< (const std::vector<DataType> &arg)
{
cout << "In vector" << endl;
return *this;
}
};
int main()
{
LoggerStream foo;
std::vector<float> v;
foo << v; // Prints "In vector", as expected
MyVector<float> w;
foo << w; // Prints "In general" (but only if the general case exists)
}
因此,使用MyVector
子类MyVector
生成对常规函数的调用,而不是对专用函数的调用。 但是,如果第一个版本被注释掉,则两个调用都将产生“向量中”。 因此,出于某种原因,两者都被认为是合适的,但是一般功能是优选的。
我仍然不知道如何在不显式写出单个子类案例的特定重载的情况下阻止这种情况的发生...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.