kafman
kafman

Reputation: 2860

C++ cannot call method (with template) from within templated method

I've got the following method within a header file called 'filter.h':

namespace std{

//some code

template <class T, class S, class BorderMethod>
tImage<T> binomial(const tImage<T> &in, const size_t k = 3) {
   //do some computations

  tImage<T> img = in.convolve<T, BorderMethod>(in, kernel);
  return img;
}
}

First thing I've noticed: the definition of this method takes place within the header-file. Is that standard procedure?

Now, the actual problem: The call to the method convolve won't work, even though in does possess such a method. Here's the definition of the method convolve within the class tImage<T>:

tImage<T> convolve(const gravis::tImage<T>& image, const gravis::tArray<typename tImageTraits<T>::Float_t>& kernel);

How do I have to call this function?

Upvotes: 5

Views: 563

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126452

First thing I've noticed: the definition of this method takes place within the header-file. Is that standard procedure?

Yes. Normally the definitions of function templates are put in headers. If they were relegated in a separate .cpp file, the compiler wouldn't be able to instantiate them implicitly when invoked, and unless you take proper action this will result in the linker complaining about undefined references. See this Q&A on StackOverflow for more information.

The call to the method convolve won't work, even though in does possess such a method.

convolve() is a non-const member function, and you are trying to invoke it through a reference to const. This is illegal and the compiler is telling you that.


Moreover, as correctly pointed out by JBentley in his answer, you cannot add new declarations or definitions to the std namespace. Per Paragraph 17.6.4.2.1/1 of the C++11 Standard:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. [...]

Upvotes: 6

JBentley
JBentley

Reputation: 6260

Although not the cause of your problem, your code has undefined behaviour because you have illegally placed it inside the std namespace.

See this question or this one.

Upvotes: 3

Related Questions