简体   繁体   中英

Specialisation for template class constructor

I am new to templates in C++. Can anyone explain why my specialised constructor never gets executed. It works when I remove the const and reference operator.

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

The output is

Template

Template

Because you cannot bind "Hello" to a const char*& .

The information dyp added in comments is quite interesting:

A string literal is an array lvalue, which can be converted to a pointer prvalue. A pointer prvalue cannot bind to a non-const lvalue reference like const char* &

Which means you can actually make it work by replacing const char*& by const char* const& , or even const char* && in c++11, not sure if this is really smart in your use case though.

UPDATE I got everything wrong, rewrote the answer completely.

First, this constructor

template<>
CData<char*>::CData(const char* &Str)

is not a specialization of CData(const T&) , because the Str parameter here is a non-const reference to pointer to const char . So it's a definition of non-templated constructor CData(const char*&) .

Second, "Hello" has type "array of n const char " (see What is the type of string literals in C and C++? ) so it can't be converted to non-const reference. This is why "Template" constructor is called.

The correct specialization is

template<>
CData<char*>::CData(char* const& Str)

That is, it accepts a const reference to char* .

And after that you should remove CData(const char*&) , unless you need for example this code to compile:

const char* foo = "foo";
CData<int> obj2(foo);

So here is the code:

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

template<typename T>
CData<T>::CData(const T& Val)
{
    ....
}

template<>
CData<char*>::CData(char* const& Str)
{
    ....
}

// warning: deprecated conversion from string constant to 'char*'
CData<char*> obj2("Hello"); // calls CData(char* const&)

The proper way of fixing above warning is to add another specialization:

template<>
CData<const char*>::CData(const char* const& Str)
{
    ...
}

CData<const char*> obj2("Hello"); // calls CData(const char* const&)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM