3

Duplicate question of this.

I have a class like this:

template <class T>
class foo {
public:        

    foo(){}

    template <int S>
    void bar (){}

}

If this class is called with:

int main(){
    foo<float> m;
    m.bar<1>();
}

It gives the error:

error: expected primary-expression before ')' token

deprecated again:

My code is:

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <boost/mpl/list.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
using namespace boost::unit_test;

#include "foo.hpp"

BOOST_AUTO_TEST_SUITE();

typedef boost::mpl::list<char, int> test_types;

BOOST_AUTO_TEST_CASE_TEMPLATE(test_Mat_constructor_hwd, T, test_types){

    foo<T> m;
    m.bar<1>();
}

BOOST_AUTO_TEST_SUITE_END()

This however does not compile as the BOOST_AUTO_TEST_CASE_TEMPLATE is doing something weird...

Following text is deprecated:

However, when I call the function with:

foo f;
f.bar<1>();

I am getting the error:

A bound member function may only be called

If I however wrap the bar function into something like void bar1(){return bar<1>();}, it would work. I know if T is not known during compile time, it will not compile. But I don't know why the compiler is not smart enough to figure out the 1 in f.bar<1> is static?

thanks!

Community
  • 1
  • 1
guinny
  • 1,522
  • 10
  • 19
  • I think you may have missed part of the error message -- that makes no sense. – Ernest Friedman-Hill Apr 28 '12 at 17:25
  • Please reduce your failing program to the shortest, **complete** program that still fails. You may discover your solution in the process. If not, please post that **short** (hint: it should be less than 20 lines), **complete** (we should be able to try to compile it) program in your question For more info, see http://sscce.org/. – Robᵩ Apr 28 '12 at 17:36
  • possible duplicate of [C++ template member function of template class called from template function](http://stackoverflow.com/questions/1840253/c-template-member-function-of-template-class-called-from-template-function) – Luc Touraille Apr 30 '12 at 15:09

2 Answers2

2

Because the T argument is unknown when parsing the test function, the compiler is unable to determine what the m.bar expression is, and therefore assumes it is a non-template variable. m.bar<1>() is therfore parsed as (m.bar<1)>(), the last bit being illegal. The fix is to explictly state that bar is a template:

foo<T> m;
m.template bar<1>();
devnev
  • 3,141
  • 1
  • 15
  • 10
1

you need to make the member functions public if you wish to call them externally, this works fine on my compiler

class foo {
public:
    foo(){}

    template <int T>
    void bar (){}
 };

int main(){
    foo f;
    f.bar<1>();
}
111111
  • 15,686
  • 6
  • 47
  • 62