Class templating std::set key types
I have a class to evaluate set algebra but wish to template it.
At the minute it looks a bit like this
set.h:
template<typename T>
class SetEvaluation
{
public:
SetEvaluation<T>();
std::set<T>
evaluate(std::string in_expression);
}
set.cpp开发者_开发问答
template<typename T>
std::set<T>
SetEvaluation<T>::evaluate(std::string expression)
{
std::set<T> result;
etc etc...
}
But i'm getting undefined reference errors when compiling.
Is it possible to declare the return type as std::set<T> and then pass std::string as the class template param.
There are no errors in the class but only when I try to instantiate SetEvaluation<std::string>
Can anyone shed light on this problem?
thanks
Template classes and functions are a bit special and need to be defined in the header file. Then that header file needs to be #included wherever you want to use that template class. If you try to define the template functions in a cpp file the linker and try to call that function from another cpp file, the linker won't be able to resolve the reference because the compiler didn't know what to use for the parameter T when it compiled the file with the template definition in it. The best way to work around this is to 1) define the function in the header file and 2) #include it wherever needed. There's further information about this issue on the C++ faq.
Trivia
There is another way to get around this using the Comeau C++ compiler because it supports the 'export' keyword, however that keyword is being deprecated in C++0X.
semicolon ; after
template<typename T>
class SetEvaluation
in .h
and define a constructor at least an empty one or comment it out
public:
SetEvaluation<T>() {}
ok, at that case use want to use this from an other file. In this case you have to explicit instantiatizate of of this template with this syntax in .cc file:
template std::set<std::string> SetEvaluation<std::string>::evaluate(std::string expression);
or you have to put the definition to the header file
For a generic solution, define your template methods as inline in the header file, either in the class body or after it: [For a given compiler system you may be able to do otherwise.]
template<typename T>
class SetEvaluation
{
public:
SetEvaluation<T>() { etc. etc.}
std::set<T>
evaluate(const std::string& in_expression);
};
template<typename T>
inline std::set<T>
SetEvaluation<T>::evaluate(const std::string& expression)
{
std::set<T> result;
// etc etc...
}
精彩评论