简体   繁体   中英

How do I specialize a member function of a template class?

template<typename _TChar>
struct simplestring
{
    void show_tstring()
    {
        throw "no implement";
    }

    void simplestring<char>::show_tstring()
    {
        cout << "char string\n";
    }

    void simplestring<wchar_t>::show_tstring()
    {
        cout << "wchar_t string\n";
    }
};


void test()
{
    simplestring<char> s;
    s.show_tstring();
}

I want to specialize the member function show_tstring of simplestring. When _TChar is char output "char string\\n" and when _TChar is wchar_t output "wchar_t string\\n". Otherwise throw an exception.

It doesn't compile with error message:

Error C2535 'void simplestring<_TChar>::show_tstring(void)': member function already defined or declared

I also tried to put the function outside the class,

void simplestring<char>::show_tstring()
{
    cout << "char string\n";
}

Compilation failed with

Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int ForTest D:\\test\\ForTest\\ForTest\\templateTest.h 848

Move the specializations outside the class body:

template<typename _TChar>
struct simplestring
{
    void show_tstring()
    {
        throw "no implement";
    }
};

template<>
void simplestring<char>::show_tstring()
{
    std::cout << "char string\n";
}

template<>
void simplestring<wchar_t>::show_tstring()
{
    std::cout << "wchar_t string\n";
}

Demo: https://godbolt.org/z/6n8E51

In your case, in C++17, you might do:

template <typename Char>
struct simplestring
{
    void show_tstring() const
    {
        if constexpr (std::is_same_v<Char, char>) {
            std::cout << "char string\n";
        } else if constexpr (std::is_same_v<Char, wchar_t>) {
            std::cout << "wchar_t string\n";
        } else {
            throw "no implement";
        }
    }
};

In C++20, you might do:

template <typename Char>
struct simplestring
{
    void show_tstring() const requires (std::is_same_v<Char, char>)
    {
        std::cout << "char string\n";
    }
    void show_tstring() const requires (std::is_same_v<Char, wchar_t>)
    {
        std::cout << "wchar_t string\n";
    }
    // nothing for other (instead of exception)
};

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