Re: Template friend function injection
H9XLrv5oXVNvHiUI@spambox.us wrote:
On Jul 11, 6:53 pm, Marcel M?ller <news.5.ma...@spamgourmet.org>
wrote:
I expected something like that. That still gives you the chance, to use
the functions defined inside Test not before the definition of test.
Furthermore you can define a template version of Function outside Test
for this purpose.
Marcel
Can you explain this point better? Especially the last sentence. If I
define a template version of Function() then I would not be able to
call it from main, am I wrong? Can you provide an example? Thank you.
template <typename T>
void Function(const T& arg);
template <typename T>
class Test
{
public:
friend void Function<T>(const T&);
};
template <typename T>
void Function(const T& arg)
{ printf("Function()"); getchar(); }
int main(int argc, char* argv[])
{
Function(Test<int>());
}
But from your question I guess that you want to do something entirely
different. You want to control by the statement
template class Test<int>;
which version of Function is implemented, isn't it? The argument list of
Function does not depend on T at all, but the body does. This is evil.
Think what is happening if you write
template class Test<int>;
template class Test<char>;
You will get an error in this case, but only if both of them are defined
in the same module. Otherwise you violate the ODR and get undefined
behavior.
In this case a simple
typedef int myFunctionType;
would do a better job.
Marcel