2

以下代码可以正确编译。

#include <string>

template <typename T, typename U>
class Container
{
private:
    T value1;
    U value2;
public:
    Container(){}
    void doSomething(T val1, U val2);
};

template<typename T, typename U>
void Container<typename T, typename U>::doSomething(T val1, U val2)
{
    ; // Some implementation
}

template <>
class Container<char, std::string>
{
private:
    char value1;
    std::string value2;
public:
    Container(){}
    void doSomething(char val1, std::string val2)
    {
        ; // Some other implementation
    }
};

但是,如果我尝试在void doSomething(char val1, std::string val2)外部定义,则会收到以下错误。

#include <string>

template <typename T, typename U>
class Container
{
private:
    T value1;
    U value2;
public:
    Container(){}
    void doSomething(T val1, U val2);
};

template<typename T, typename U>
void Container<typename T, typename U>::doSomething(T val1, U val2)
{
    ; // Some implementation
}

template <>
class Container<char, std::string>
{
private:
    char value1;
    std::string value2;
public:
    Container(){}
    void doSomething(char val1, std::string val2);
};

template<>
void Container<char,std::string>::doSomething(char val1, std::string val2)
{
    ; // Some other implementation
}

错误:

错误 1 ​​错误 C2910: 'Container::doSomething' : 不能明确专门化 c:\users\bharani\documents\visual studio 2005\projects\templates\template specialization\templatespecializationtest.cpp 35

我犯了什么错误?

谢谢。

4

1 回答 1

6

您没有明确专门化成员函数。但是您正在定义显式(类模板)专业化的成员函数。那是不同的,你需要像这样定义它

inline void Container<char,std::string>::doSomething(char val1, std::string val2)
{
    ; // Some other implementation
}

请注意,“内联”很重要,因为这不是模板,如果在类外部定义它也不是隐式内联的。如果将标头包含在多个翻译单元中,则需要内联以避免重复的链接器符号。

您是否在显式专业化中有一个模板,必须使用您的语法:

template <>
class Container<char, std::string>
{
private:
    char value1;
    std::string value2;
public:
    Container(){}

    template<typename T, typename U>
    void doSomething(T val1, U val2) { /* primary definition */ }
};

template<>
inline void Container<char,std::string>::doSomething(char val1, std::string val2)
{
    ; // Some other implementation
}

您的第一个代码中也有错误。您需要像这样定义类外定义,在类模板的参数列表中没有“typename”

template<typename T, typename U>
void Container<T, U>::doSomething(T val1, U val2) 
{
    ; // Some implementation
}
于 2010-08-27T17:00:16.803 回答