c++ - 防止调用模板化复制构造函数

标签 c++ templates

下面调用了模板复制构造函数。

#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;
}

如何防止调用模板化复制构造函数?我期望因为 BA 类型,并且我通过引用传递,所以不会调用任何构造函数。我创建了一个专门的复制构造函数,希望它能被调用:

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
{
}

DEMO


We are not using C++0x

你可以自己写enable_ifis_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++98 DEMO

关于c++ - 防止调用模板化复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003687/

相关文章:

c++ - 如何解析 "invalid operands of types ' const char [ ]' and ' const char *' to binary ' operator +' "

c++ - 记录跨越多个文件的 namespace doxygen

c++ - 是什么让boost::shared_mutex如此缓慢

c++ - 为什么说C++不支持参数多态?

C++ 可变参数模板打包到 std::array 并解包

c++ - 递归模板成语如何避免基类是子类的 friend

templates - 转到模板 : looping over index

c++ - GMP:得到差异的绝对值?

c++ - 捕获可变参数模板类型?

c++ - 在接口(interface)映射遗留 C 接口(interface)中使用模板参数化类型