模板类构造函数的专业化

Nid*_* MS 3 c++ templates partial-specialization template-specialization

我是C++模板的新手.谁能解释为什么我的专用构造函数永远不会被执行.它删除const和引用运算符时工作.

#include<iostream>
#include<string>

using namespace std;

template<typename T>
class CData
{
public:
    CData(const T&);
    CData(const char*&);
private:
    T m_Data;
};

template<typename T>
CData<T>::CData(const T& Val)
{
    cout << "Template" << endl;
    m_Data = Val;
}
template<>
CData<char*>::CData(const char* &Str)
{
    cout << "Char*" << endl;
    m_Data = new char[strlen(Str) + 1];
    strcpy(m_Data, Str);
}

void main()
{
    CData<int> obj1(10);
    CData<char*> obj2("Hello");
}
Run Code Online (Sandbox Code Playgroud)

输出是

模板

模板

Dra*_*rax 5

因为你无法绑定"Hello"const char*&.

评论中添加的信息dyp非常有趣:

字符串文字是一个数组左值,可以转换为指针prvalue.指针prvalue不能绑定到非const左值引用,如const char*&

这意味着你实际上可以让它通过更换工作const char*&const char* const&,甚至const char* &&在C++ 11,不知道这是在你的使用情况真的很聪明,虽然.