【问题标题】:Template specialization: non-inline function definition issue模板专业化:非内联函数定义问题
【发布时间】:2010-08-28 01:05:28
【问题描述】:

以下代码编译正确。

#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: '容器::doSomething' : 不能明确 专门的 c:\users\bharani\documents\visual 工作室 2005\项目\模板\模板 专业化\模板专业化测试.cpp 35

我犯了什么错误?

谢谢。

【问题讨论】:

    标签: c++ templates template-specialization


    【解决方案1】:

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

    一样定义它
    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
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多