bdh*_*har 2 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
}
};
Run Code Online (Sandbox Code Playgroud)
但如果我尝试在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
}
Run Code Online (Sandbox Code Playgroud)
错误:
错误1错误C2910:'Container :: doSomething':无法显式专门化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
}
Run Code Online (Sandbox Code Playgroud)
请注意,"内联"很重要,因为它不是模板,如果它是在类外部定义的,则它不是隐式内联的.如果将标头包含在多个转换单元中,则需要内联以避免重复的链接器符号.
你有明确的专业化模板,你的语法必须使用:
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
}
Run Code Online (Sandbox Code Playgroud)
您的第一个代码中也有错误.您需要像这样定义类外定义,而不在类模板的参数列表中使用"typename"
template<typename T, typename U>
void Container<T, U>::doSomething(T val1, U val2)
{
; // Some implementation
}
Run Code Online (Sandbox Code Playgroud)