我有一个模板化的方法,我希望它根据模板调用不同的方法。我这样做的原因是,调用方不需要创建B类型的对象,只需获得正确的实现调用,而是应该能够通过模板按实现进行选择。
问题是,我正在接收const的引用类型作为模板T,并且我不知道如何使用它来选择正确的重载方法。理想情况下,如果T不是引用类型,这也是可行的。有什么想法吗?
注意:我不能使用模板专门化,因为我需要impl虚拟。
#include <iostream>
using namespace std;
class A {};
class B {};
class C {
public:
template <typename T>
void f() {
// T = const B&
impl(T()); // error: value-initialization of reference type ‘const B&’
}
protected:
virtual void impl(const A& a) {
cout << "A";
}
virtual void impl(const B& b) {
cout << "B";
}
};
int main() {
C c;
const B &b2 = B();
c.f<decltype(b2)>(); // T = const B&
return 0;
}发布于 2013-12-11 21:08:36
如果希望获得更可能是可构造的类型,则应该删除任何引用,例如使用std::remove_reference<T>和所有限定符,例如使用std::remove_cv<T>。..。或者,只需将数组转换为指针的类型std::decay<T>:
template <typename T>
void f() {
impl(typename std::decay<T>::type());
}发布于 2013-12-11 21:10:49
您仍然可以通过助手专用模板分派程序使用模板专门化来调用正确版本的impl -该版本仍然可以是虚拟的。像这样,编译和运行
#include <iostream>
using namespace std;
class A {};
class B {};
class C {
public:
template <typename T>
void f() {
// T = const B&
impl_dispatch<T>(); // error: value-initialization of reference type ‘const B&’
}
protected:
virtual void impl(const A& a) {
cout << "A";
}
virtual void impl(const B& b) {
cout << "B";
}
private:
template <typename T>
void impl_dispatch();
};
template <> void C::impl_dispatch<A const &>()
{
impl(B());
}
template <> void C::impl_dispatch<B const &>()
{
impl(A());
}
int main() {
C c;
const B &b2 = B();
c.f<decltype(b2)>(); // T = const B&
return 0;
}https://stackoverflow.com/questions/20529836
复制相似问题