Error with member function template - c++

I am getting compilation error in below code.
class A
{
public:
A()
{
}
~A()
{
}
void func()
{
cout <<"Ha ha ha \n";
}
};
class C
{
public:
C()
{
}
~C()
{
}
template<typename type> func()
{
type t;
t.func();
}
void callme()
{
func<A>();
}
};

VC6 doesn't support member function templates. You actually have several solutions:
Move func() out of the class definition
template<typename type> void func()
{
type t;
t.func();
}
or rewrite callme()
void callme()
{
A a;
a.func();
}
or use class template
class C
{
public:
template<class T> struct func
{
void operator()()
{
T t;
t.func();
}
};
void callme()
{
func<A>()();
}
};

The definition of func<T>() doesn't specify its return type, which is invalid in C++.
It should be:
template<typename type> void func()
{
type t;
t.func();
}

Related

Calling a callback passed from another class

I want to register a callback handler (method) of the one class (Y) in another (X). I can't use std::function because of possible heap allocation and I must have an access to members of a class that registers the handler. I also want to avoid static functions.
I've came up with some workaournd but got stuck on calling the callback:
template<class T>
using clbkType = void(T::*)(void);
template<class T>
class X
{
public:
void registerClbck(clbkType<T> clbk) {
callback = clbk;
}
void call() {
callback(); // ERROR C2064: term does not evaluate to a function taking 0 arguments.
//(((X<T>*)this)->X<T>::callback)(); // same error
}
private:
clbkType<T> callback;
};
class Y
{
public:
Y() {
x.registerClbck(&Y::handler);
}
// just for a test: fire a callback in class X
void fire() {
x.call();
}
int getA() { return a; }
private:
int a{ 0 };
X<Y> x{};
void handler() {
a = 5;
}
};
int main()
{
Y y;
y.fire();
return y.getA();
}
link to code: https://godbolt.org/z/PhY41xsWE
PS. I'm not sure if this is a safe solution, so please put any comment on that.
Thanks!
The member function pointer needs a specific class object to invoke, so you need to do this:
template<class T>
class X
{
public:
// ...
void call(T& obj) {
(obj.*callback)();
}
// ...
};
class Y
{
public:
// just for a test: fire a callback in class X
void fire() {
x.call(*this);
}
// ...
};
Demo.
The member function pointer need an instance to be called on.
If you want to bind the instance, here is a possible way to implement it.
template<typename T>
struct member_callback {
T* instance;
void(T::*callback)();
void operator()(){(instance->*callback)();}
};
template<typename T>
struct X{
void registerClbck(member_callback<T> clbk) { callback = clbk; }
void call() { callback(); }
member_callback<T> callback;
};
struct Y{
public:
Y() { x.registerClbck({this,&Y::handler}); }
void fire() { x.call(); }
int getA() { return a; }
private:
int a{ 0 };
X<Y> x{};
void handler(){ a = 5; }
};
int main()
{
Y y;
y.fire();
return y.getA();
}

Polymorphic function call without duplicate code

Suppose that all classes of a hierarchy implement a template member function g. All classes share the same implementation of two other functions f1 and f2 that call this template:
struct A {
virtual void f1() {
g(5);
}
virtual void f2() {
g(5.5);
}
private:
template <typename T> void g(T) {std::cout << "In A" << std::endl;}
};
struct B: A {
// Can I get rid of this duplicate code?
virtual void f1() {
g(5);
}
virtual void f2() {
g(5.5);
}
private:
template <typename T> void g(T) {std::cout << "In B" << std::endl;}
};
struct C: A {
// Can I get rid of this duplicate code?
virtual void f1() {
g(5);
}
virtual void f2() {
g(5.5);
}
private:
template <typename T> void g(T) {std::cout << "In C" << std::endl;}
};
int main()
{
B b;
A &a = b;
a.f1();
return 0;
}
Since the implementations of f1 and f2 are identical in all the classes, how can I get rid of the duplicate code and still have the polymorphic call in main work as expected (i.e produce the output "In B")?
Note that the implementations of f1 and f2 in A, B, and C are not identical. Let's restrict it to f1s. One calls a function named ::A::g<int>, another one calls a function named ::B::g<int>, and the third one calls a function named ::C::g<int>. They are very far from identical.
The best you could do is have a CRTP-style base:
template <class Derived>
struct DelegateToG : public A
{
void f1() override
{
static_cast<Derived*>(this)->g(5);
}
void f2() override
{
static_cast<Derived*>(this)->g(5.5);
}
};
class B : public DelegateToG<B>
{
friend DelegateToG<B>;
private:
template <class T> void g(T) { /*...*/ }
};
class C : public DelegateToG<C>
{
friend DelegateToG<C>;
private:
template <class T> void g(T) { /*...*/ }
};
You can just factor out the class-specific things that the template function uses, such as (in your example) the class name:
#include <iostream>
using namespace std;
class A
{
private:
virtual auto classname() const -> char const* { return "A"; }
protected:
template <typename T> void g(T) {cout << "In " << classname() << endl;}
public:
virtual void f1() { g(5); }
virtual void f2() { g(5.5); }
};
class B
: public A
{
private:
auto classname() const -> char const* override { return "B"; }
};
class C
: public A
{
private:
auto classname() const -> char const* override { return "C"; }
};
auto main()
-> int
{ static_cast<A&&>( B() ).f1(); }

Is a C++ template able to "forward any class function" from parent class?

class Foo {
public:
void methodA();
};
class ManagedFoo {
Foo fooInst;
public:
void methodA() { doSomething(); fooInst.methodA();}
};
Now I want to make ManagedFoo as a template, managing any class not only Foo, and before any of Foo's function is called, call doSomething first.
template<typename _TyManaged>
class Manager {
_TyManaged _managedInst;
void doSomething();
public:
/*Forward every function called by _managedInst*/
/*How to write this?*/
};
I want to make it the same, make it replaceable between this two class, like this :
Foo* foo = new Foo();
foo->methodA();
Manager<Foo> managedFoo = new Manager<Foo>();
managedFoo->methodA(); //Hope it call Manager::doSomething() first then call _managedInst.methodA();
Can C++11 template do such thing? if answer is yes, how to?
Solution based on operator-> overloading:
#include <iostream>
#include <memory>
class A {
public:
void foo() { std::cout << "foo\n"; }
void bar() { std::cout << "bar\n"; }
};
template <typename T>
class ManagedBase {
std::shared_ptr<T> _inst;
public:
ManagedBase(const std::shared_ptr<T> inst) : _inst(inst) { }
virtual ~ManagedBase() { }
std::shared_ptr<T> operator->() {
before();
return this->_inst;
}
virtual void before() =0;
};
template <typename T>
class ManagedPrint : public ManagedBase<T> {
public:
ManagedPrint(const std::shared_ptr<T> inst) : ManagedBase(inst) { }
virtual void before() {
std::cout << "Said: ";
}
};
int main() {
auto ma = ManagedPrint<A>(std::make_shared<A>());
ma->bar(); // Said: foo
ma->bar(); // Said: bar
}
Something like this?
template<typename _TyManaged>
class Manager {
_TyManaged _managedInst;
void doSomething();
public:
_TyManaged* operator->() {
doSomething();
return &_managedInst;
}
};
This can solve your problem. But I'm still not sure what you want to do with your Manager class.
class Foo {
public:
void methodA();
};
template<typename T>
class ManagedFoo : public T {
public:
// some further extensions
};
And of course in this way you change the semantic of the Foo class by the manager from:
It has a
to
It is a
So I'm not sure if this is true in your case.

Overriding a method returning typename T does not work

#include <iostream>
#include <string>
using namespace std;
template <typename T>
class A
{
public:
A()
{
OverrideMe();
}
virtual ~A(){};
virtual T OverrideMe()
{
throw string("A.OverrideMe called");
}
protected:
T member;
};
class B : public A<double>
{
public:
B(){};
virtual ~B(){};
virtual double OverrideMe()
{
throw string("B.OverrideMe called");
}
};
int main()
{
try
{
B b;
}
catch(string s)
{
cout << s << endl; //this prints: A.OverrideMe called
}
return 0;
}
You can override a method from a template base class, as can be shown in this example:
#include <iostream>
template <typename T> struct Foo
{
virtual T foo() const {
std::cout << "Foo::foo()\n";
return T();
}
};
struct Bar : Foo<double>
{
virtual double foo() const {
std::cout << "Bar::foo()\n";
return 3.14;
}
};
int main(){
Bar b;
double x = b.foo();
}
output:
Bar::foo()
I'm suspecting (out of the blue) that your type T is declared but not defined.

C++ template instantiation restrictions

I have a method foo in class C which either calls foo_1 or foo_2.
This method foo() has to be defined in C because foo() is pure virtual in BaseClass and I actually
have to make objects of type C. Code below:
template <class T>
class C:public BaseClass{
void foo() {
if (something()) foo_1;
else foo_2;
}
void foo_1() {
....
}
void foo_2() {
....
T t;
t.bar(); // requires class T to provide a method bar()
....
}
};
Now for most types T foo_1 will suffice but for some types foo_2 will be called
(depending on something()). However the compiler insists on instantiating both foo_1
and foo_2 because either may be called.
This places a burden on T that it has to provide
a bar method.
How do I tell the compiler the following:
if T does not have bar(), still allow it as an instantiating type?
you could use boost.enable_if. something like this:
#include <boost/utility/enable_if.hpp>
#include <iostream>
struct T1 {
static const bool has_bar = true;
void bar() { std::cout << "bar" << std::endl; }
};
struct T2 {
static const bool has_bar = false;
};
struct BaseClass {};
template <class T>
class C: public BaseClass {
public:
void foo() {
do_foo<T>();
}
void foo_1() {
// ....
}
template <class U>
void foo_2(typename boost::enable_if_c<U::has_bar>::type* = 0) {
// ....
T t;
t.bar(); // requires class T to provide a method bar()
// ....
}
private:
bool something() const { return false; }
template <class U>
void do_foo(typename boost::enable_if_c<U::has_bar>::type* = 0) {
if (something()) foo_1();
else foo_2<U>();
}
template <class U>
void do_foo(typename boost::disable_if_c<U::has_bar>::type* = 0) {
if (something()) foo_1();
// I dunno what you want to happen if there is no T::bar()
}
};
int main() {
C<T1> c;
c.foo();
}
You could create an interface for foo_1 and foo_2, such as:
class IFoo
{
public:
virtual void foo_1()=0;
virtual void foo_2()=0;
};
template <typename T>
class C : public BaseClass, public IFoo
{
void foo()
{
if (something())
foo_1();
else
foo_2();
}
};
template <typename T>
class DerivedWithBar : C<T>
{
public:
void foo_1() { ... }
void foo_2()
{
...
T t;
t.bar(); // requires class T to provide a method bar()
...
}
};
template <typename T>
class DerivedNoBar : C<T>
{
public:
void foo_1() { ... }
void foo_2() { ... }
};
I think the easiest way is to simply write a separate function template that 'C' can call:
template <class T>
void call_bar(T& /*t*/)
{
}
template <>
void call_bar<Something>(Something& t)
{
t.bar();
}
The original 'C' class can be modified accordingly:
void foo_2() {
....
T t;
call_bar(t); // does not require T to provide bar()
....
}
This has the downside that you have to explicitly define which types of T provide a bar method, but that's pretty much inevitable unless you can determine something at compile-time about all the types that do provide a bar method in their public interface or modify all these bar-supporting types so that they do share something in common that can be determined at compile-time.