J
jack
Hi there,
I have a short question about template function
definition.
1) The following files will not compile in M$ VC++
but will have no problem with g++.
2) However, if I uncomment all comments in all three
files, then it is ok in both compilers.
I am confused. What should a good compiler do
in both cases?
If the definition of a template
function should always reside in the header file,
why does it help by adding a "wrapper" function
for a template function, after I put its definition
in the wrong place (source file)?
Thank you for your help!
========================= file driver.cpp
#include <iostream>
#include "func.h"
using namespace std;
int main()
{
cout << tf(TwoToOne(g, 2.3), 1.5) << endl;
// cout << ff(1.5) << endl;
return 0;
}
========================== file func.h
#ifndef FUNC_H
#define FUNC_H
class TwoToOne
{
public:
double (*m_f)(double, double);
double m_op;
TwoToOne(double (*f) (double, double), double op)
{
m_f = f;
m_op = op;
}
double operator()(double x)
{
return m_f(x, m_op);
}
};
double g(double x, double y);
template <class T>
double tf(T f, double x);
// double ff(double x);
#endif
============================ file func.cpp
#include "func.h"
double g(double x, double y)
{
return x*x + y;
}
template <class T>
double tf(T f, double x)
{
return f(x);
}
/*
double ff(double x)
{
return tf(TwoToOne(g, 2.3), x);
}
*/
I have a short question about template function
definition.
1) The following files will not compile in M$ VC++
but will have no problem with g++.
2) However, if I uncomment all comments in all three
files, then it is ok in both compilers.
I am confused. What should a good compiler do
in both cases?
If the definition of a template
function should always reside in the header file,
why does it help by adding a "wrapper" function
for a template function, after I put its definition
in the wrong place (source file)?
Thank you for your help!
========================= file driver.cpp
#include <iostream>
#include "func.h"
using namespace std;
int main()
{
cout << tf(TwoToOne(g, 2.3), 1.5) << endl;
// cout << ff(1.5) << endl;
return 0;
}
========================== file func.h
#ifndef FUNC_H
#define FUNC_H
class TwoToOne
{
public:
double (*m_f)(double, double);
double m_op;
TwoToOne(double (*f) (double, double), double op)
{
m_f = f;
m_op = op;
}
double operator()(double x)
{
return m_f(x, m_op);
}
};
double g(double x, double y);
template <class T>
double tf(T f, double x);
// double ff(double x);
#endif
============================ file func.cpp
#include "func.h"
double g(double x, double y)
{
return x*x + y;
}
template <class T>
double tf(T f, double x)
{
return f(x);
}
/*
double ff(double x)
{
return tf(TwoToOne(g, 2.3), x);
}
*/