下面调用了模板复制构造函数。
#include <iostream>
using namespace std;
class A
{
public:
A(){ cout << "Class A constructor\n";}
A(const A &a){ cout << "Class A copy constructor\n"; }
};
class B : public A
{
public:
B(){ cout << "Class B constructor\n";}
B(const B &a){ cout << "Class B copy constructor\n"; }
};
template <typename T>
class Template
{
public:
Template() { cout << "Template default\n"; }
Template(const Template &a) { cout << "Template copy constructor\n"; }
// This gets called
template <typename T2>
Template(const Template<T2> &a)
{
cout << "Templated template copy constructor\n";
}
};
void funcT(const Template<A> &a)
{
}
int main()
{
Template<B> bt;
cout << "Calling funcT(bt)\n";
funcT(bt);
return 0;
}
如何防止调用模板化复制构造函数?我期望因为 B
是 A
类型,并且我通过引用传递,所以不会调用任何构造函数。我创建了一个专门的复制构造函数,希望它能被调用:
Template(const Template<A> &a)
{
cout << "Specialized templated template copy constructor\n";
}
但这并不能编译。
基本上,我不想在调用funcT()
时调用现有的三个构造函数。
最佳答案
您可以使您的函数成为接受任何 Template<T>
的模板。 但只有当 T
继承自 A
,因此不会进行复制/转换:
#include <type_traits>
template <typename T>
auto funcT(const Template<T>& a)
-> typename std::enable_if<std::is_base_of<A, T>::value>::type
{
}
We are not using C++0x
你可以自己写enable_if
和 is_base_of
:
template <bool b, typename T = void>
struct my_enable_if {};
template <typename T>
struct my_enable_if<true, T> { typedef T type; };
template <typename Base, typename Derived>
struct my_is_base_of
{
static char test(Base*);
static long test(...);
static const bool value = sizeof(test((Derived*)0)) == sizeof(char);
};
template <typename T>
typename my_enable_if<my_is_base_of<A, T>::value>::type funcT(const Template<T>& a)
{
}
关于c++ - 防止调用模板化复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003687/