I have two classes test1 and test2:
struct test1
{
int r;
test1() {}
test1(int value) : r(value) {}
test1 foo() const;
};
struct test2
{
int r;
test2() {}
test2(int value) : r(value) {}
};
template <typename t>
struct data_t
{
static const t one;
};
template <> const test1 data_t<test1>::one = test1(1);
template <> const test2 data_t<test2>::one = test2(1);
then i created a function to do somthing:
template <typename t, const t& value>
t do_somthing()
{ return value; };
the action of do_something is straightforward, it returns a copy of value, so in main function:
int main()
{
test1 r = do_somthing<test1, data_t<test1>::one>();
}
the problem happens when implementing test1::foo
test1 test1::foo() const
{ return do_somthing<test1, *this>(); }
the compiler stops with error:
'this' : can only be referenced inside non-static member functions
with *this it becomes test1 const& which acceptable as 2nd parameter, so why this error?
When you call a
templatemethod with explicit mention of parameters like,then compiler expects that the explicit arguments should be compile time constants. In your (2)nd case,
*thisis not resolvable to a compile time constant, so you are getting the compiler error.Change the definition to below:
and now when you call as,
it should work. Because, now
const t&doesn’t need to be a compile time constant, even though it’s resolved at compile time.