c++ - 模板特化 : non-inline function definition issue

标签 c++ templates template-specialization

以下代码可以正确编译。

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

错误:

Error 1 error C2910: 'Container::doSomething' : cannot be explicitly specialized c:\users\bharani\documents\visual studio 2005\projects\templates\template specialization\templatespecializationtest.cpp 35

我犯了什么错误?

谢谢。

最佳答案

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

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
}

关于c++ - 模板特化 : non-inline function definition issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3586467/

相关文章:

c++ - 基类模板中的从属名称查找

c++ - 特化一个函数模板

c++ - 为什么我不能专门化功能模板?

c++ - 类和成员函数模板特化出错

c++ - 如何使用签名 `object ()` 模拟函数

c++ - 使用 MySQL++ 抛出 EXC_BAD_ACCESS

java - 静态类型和编写简单的矩阵库

C++ 设置 TDateTime 变量

excel - ComponentArt:导出网格数据

c++ - 删除模板化结构偏特化