I have the following code (very simplified for the sake of clarity):
class Base
{
virtual int DoStuff(int arg) = 0;
};
template <typename T>
class Derived : public Base
{
int DoStuff(int arg) override
{
// do some stuff
return 0;
}
};
This works great. Now I want to implement a special (vectorized) implementation of DoStuff. And I need the implementation to be specific based on the type T that Derived has, something like this:
class Base
{
virtual int DoStuff(int arg) = 0;
virtual int DoStuffVectorized(int arg) = 0;
};
template <typename T>
class Derived : public Base
{
int DoStuff(int arg) override
{
// do some stuff
return 0;
}
int DoStuffVectorized<char>(int arg) override
{
// do some stuff for T == char
return 0;
}
int DoStuffVectorized<int>(int arg) override
{
// do some stuff for T == int
return 0;
}
};
However i'm unable to make this work.
EDIT:
I get the following error message: error C2143: syntax error: missing ';' before '<' on the line int DoStuffVectorized<char>(int arg) override.
When i change it to:
template<char> int DoStuffVectorized(int arg) override i get: error C2898: ...': member function templates cannot be virtual
Any advice on how to achieve something like this? The reason i need it is that i have a std::vector that stores data of various types (by using Derived<>). This way i can use the same simple code regardless of the type being stored and i want this to be true even when using the special vectorized implementation of DoStuff that is sadly type specific.
You have to specialize template member functions outside of the class:
#include <iostream>
class Base
{
public:
virtual int DoStuffVectorized(int arg) = 0;
};
template <typename T>
class Derived : public Base
{
public:
int DoStuffVectorized(int arg) override;
};
template <>
int Derived<char>::DoStuffVectorized(int arg)
{
std::cout << "T == char\n";
return 0;
}
template <>
int Derived<int>::DoStuffVectorized(int arg)
{
std::cout << "T == int\n";
return 0;
}
int main(){
Derived<char> c;
Derived<int> i;
Base* b[] = { &c, &i };
for(auto* x : b)
x->DoStuffVectorized(0);
// undefined reference to `Derived<double>::DoStuffVectorized(int)'
// Derived<double> d;
}
If you want to capture unintended instantiations at compile time:
#include <type_traits>
// A std::false_type (useful in a static_assert)
template <typename T>
struct static_false : std::false_type
{};
template <typename T>
int Derived<T>::DoStuffVectorized(int arg)
{
static_assert(static_false<T>::value, "Neither 'char' or 'int'");
return 0;
}
DoStuffVectorized<char> is not correct syntax, DoStuffVectorized isn't template itself.
See template specialization:
template <typename T>
class Derived : public Base
{
int DoStuff(int arg) override
{
// do some stuff
return 0;
}
int DoStuffVectorized(int arg) override
{
// do some stuff (primary template)
return 0;
}
};
template <>
int Derived<int>::DoStuffVectorized(int) {
// do some stuff for T == char
return 0;
}
template <>
int Derived<char>::DoStuffVectorized(int) {
// do some stuff for T == char
return 0;
}
Related
I've got an abstract class that uses variable template.
template <class T>
class Abstract
{
public:
virtual void print(T t) = 0;
};
There can be any derivatives of the class like so:
class A : public Abstract<std::string>
{
public:
void print(std::string str)
{
std::cout << str << std::endl;
}
};
class B : public Abstract<int>
{
public:
void print(int number)
{
std::cout << std::to_string(number) << std::endl;
}
};
Now I want a function to return one of these derivatives so I can execute the print method. And here is my Problem:
template (class T); // error here
Abstract<T> &f(int n) // what should the return type look like?
{
if (n == 0)
{
A a{};
return a;
}
else
{
B b{};
return b;
}
}
int main()
{
A a{f(0)};
a.print("foo");
B b{f(1)};
b.print(42);
return 0;
}
So how is it be possible to return a class with unknown parameter type and call its methods?
I already tried returning derived classes without templates which works fine. As soon as templates are added code wont compile. I also tried void* and reinterpret_cast. Problem here is that I have manually to decide to what type to cast to.
So how can I return an arbitrary superclass of an abstract generic class and call its generic methods?
I think inheritance is the wrong approach here. Instead I would use specialization instead:
template<typename T>
struct Foo;
template<>
struct Foo<std::string>
{
void print(std::string const& s)
{
std::cout << s << '\n';
}
};
template<>
struct Foo<int>
{
void print(int value)
{
std::cout << value << '\n';
}
};
Then you don't need a selector to pick the object to create, just the correct type:
int main()
{
Foo<std::string> f1;
f1.print("hello");
Foo<int> f2;
f2.print(123);
}
If you really need a factor function, then it could be created like this:
template<typename T>
Foo<T> create()
{
return Foo<T>();
}
And use like
int main()
{
auto f1 = create<std::string>();
f1.print("hello");
auto f2 = create<int>();
f2.print(123);
}
I have a template class C<T> which I intend to instantiate with T as some other classes A and B. C<T> has a method foo whose signature I would like to depend on whether T was instantiated as A or B. For example, consider the following code:
#include <iostream>
#include <string>
class A {
public:
void message() {
std::cout << "message with no args" << std::endl;
}
};
class B {
public:
void message(int x) {
std::cout << "message with " << x << std::endl;
}
};
template<typename T>
class C {
private:
T internal;
public:
C(T& x) {
internal = x;
}
void call() {
internal.message();
}
void call(int x) {
internal.message(x);
}
};
int main(int argc, char* argv[]) {
A a;
B b;
C<A> ca(a);
C<B> cb(b);
ca.call();
cb.call(42);
// ca.call(42); ERROR HERE
return 0;
}
This runs correctly. ca.call(42) would raise a compilation error because there is no method A::message(int). However, if I for some reason introduce a method A::message(int) in A, the code may allow calling ca.call(42), which I would like to prevent.
I know that SFINAE techniques would allow to declare a method C::call(T::call_type x) where T::call_type would be a typedef for each intended instantiation of T. However, this only allows me to change the type of the argument of C::call. I would like instead to make the signature (in particular, the number of parameters) of C::call on T. I would thus prevent ca.call(42) from being a valid call even if there is a method A::message(int) in A.
Is there any way to do this?
I don't know all the ins and outs of SFINAE, but what do you think of this?
template <
typename = std::enable_if_t<std::is_same<std::decay_t<T>, A>::value>>
void call() {
internal.message();
}
template <
typename = std::enable_if_t<std::is_same<std::decay_t<T>, B>::value>>
void call(int x) {
internal.message(x);
}
You can use == false too
template <
typename = std::enable_if_t<std::is_same<std::decay_t<T>, B>::value == false>>
You can do this with template specializations:
// Main template used by every other type T.
template<typename T>
class C; // or some other implementation.
// This gets used for T = A.
template<>
class C<A> {
private:
A internal;
public:
C(A& x) {
internal = x;
}
void call() {
internal.message();
}
};
// This gets used for T = B.
template<>
class C<B> {
private:
B internal;
public:
C(B& x) {
internal = x;
}
void call(int x) {
internal.message(x);
}
};
If you don't like that you need to duplicate some common code, then you can have a base class with all those common things and inherit from it in each specialization.
I am using C++ and templates - but I need to allow using a member function for a specific type and prevent other types from using this function.
For example: I want this class to have print() for all types but have foo() for just type int. How can I do that ?
#include<iostream>
template <class type>
class example
{
private:
type data;
public:
void print(); // for all types
void foo(); // only for 'type' == int?
};
Factor the common, generic functionality into a base class. Specializations can inherit that.
namespace detail {
template <class type>
class example_base
{
private:
type data ;
public:
void print();
};
} // end namespace detail
template <class type>
struct example
: detail::example_base<type> {
using detail::example_base<type>::example_base; // inherit any constructors
};
template <> // specialize the class
struct example< int >
: detail::example_base<int> {
using detail::example_base<int>::example_base; // inherit any constructors
void other_function(); // extend the basic functionality
};
You can specify the template for some types. See this example :
template <typename T>
class MyClass
{
private:
double my_function() { return 1.0; }
};
template <>
class MyClass<double>
{
public:
double my_function() { return 2.0; }
};
int main()
{
MyClass<double> a;
MyClass<int> b;
double x = a.my_function(); // this works
// double y = b.my_function(); // not allowed
return 0;
}
Tested with GCC 4.7.2.
You could use std::enable_if and do something like this to obtain exactly what you want:
#include <iostream>
#include <type_traits>
template<class T>
class example
{
private:
T data;
public:
void print()
{
std::cout << " hello " << std::endl;
}
template<class U = T // make the function templated on U, but with default type T
, typename std::enable_if<std::is_integral<U>::value>::type* = nullptr // enable only for when U (T) is an integral type
>
void foo()
{
std::cout << " I will only compile when T is an integral type " << std::endl;
}
};
int main()
{
example<int> integer_example;
integer_example.print();
integer_example.foo(); // <--- compiles fine as int is integral
example<double> double_example;
double_example.print();
//double_example.foo(); // <--- will not compile
return 0;
}
In the std::enable_if you can also put std::is_same<U,int>::value instead of std::is_integral<U>::value to only allow the function only to be used for int and not other integral types.
I have learned this code like inheritance by using template technique on C++. This code works.
#include <iostream>
using namespace std;
template < typename T >
class Base {
public:
explicit Base(const T& policy = T()) : m_policy(policy) {}
void doSomething()
{
m_policy.doA();
m_policy.doB();
}
private:
T m_policy;
};
class Implemented {
public:
void doA() { cout << "A"; };
void doB() { cout << "B"; };
};
int main() {
Base<Implemented> x;
x.doSomething();
return 0;
}
However, is it possible to add arguments with new typename S in doA and doB? For example, this code doesn't work by type/value mismatch errors.
#include <iostream>
using namespace std;
template < typename T, typename S >
class Base {
public:
explicit Base(const T& policy = T()) : m_policy(policy) {}
void doSomething()
{
m_policy.doA(m_s);
m_policy.doB(m_s);
}
private:
T m_policy;
S m_s;
};
template < typename S >
class Implemented {
public:
void doA(S& s) { cout << "A" << s; };
void doB(S& s) { cout << "B" << s; };
};
int main() {
Base<Implemented, int> x;
x.doSomething();
return 0;
}
I guess I must let both class Base and Implemented know about an actual type of S at main(). How can I fix this issue? Thank you for your help in advance.
In this line:
Base<Implemented, int> x;
Implemented is no longer a type, now you made it a template. But Base still expects a type - so give it one:
Base<Implemented<int>, int> x;
When Implemented was a class, you used a template parameter T. Now that Implmented is a template class, you need to use a so called template template parameter, like so:
#include <iostream>
using namespace std;
template < template <class TS> class T, typename S >
class Base {
public:
explicit Base(const T<S>& policy = T<S>()) : m_policy(policy) {}
void doSomething()
{
m_policy.doA(m_s);
m_policy.doB(m_s);
}
private:
T<S> m_policy;
S m_s;
};
template < typename S >
class Implemented {
public:
void doA(S& s) { cout << "A" << s; };
void doB(S& s) { cout << "B" << s; };
};
int main() {
Base<Implemented, int> x;
x.doSomething();
return 0;
}
Following code does NOT work, but it expresses well what I wish to do. There is a problem with the template struct container, which I think SHOULD work because it's size is known for any template argument.
class callback {
public:
// constructs a callback to a method in the context of a given object
template<class C>
callback(C& object, void (C::*method)())
: ptr.o(object), ptr.m(method) {}
// calls the method
void operator()() {
(&ptr.o ->* ptr.m) ();
}
private:
// container for the pointer to method
template<class C>
struct {
C& o;
void (C::*m)();
} ptr;
};
Is there any way to do such a thing? I mean have a non-template class callback which wraps any pointer to method?
Thanks C++ gurus!
Edit:
Please see this:
Callback in C++, template member? (2)
This is a complete working example that does what I think you're trying to do:
#include <iostream>
#include <memory>
// INTERNAL CLASSES
class CallbackSpecBase
{
public:
virtual ~CallbackSpecBase() {}
virtual void operator()() const = 0;
};
template<class C>
class CallbackSpec : public CallbackSpecBase
{
public:
CallbackSpec(C& o, void (C::*m)()) : obj(o), method(m) {}
void operator()() const { (&obj->*method)(); }
private:
C& obj;
void (C::*method)();
};
// PUBLIC API
class Callback
{
public:
Callback() {}
void operator()() { (*spec)(); }
template<class C>
void set(C& o, void (C::*m)()) { spec.reset(new CallbackSpec<C>(o, m)); }
private:
std::auto_ptr<CallbackSpecBase> spec;
};
// TEST CODE
class Test
{
public:
void foo() { std::cout << "Working" << std::endl; }
void bar() { std::cout << "Like a charm" << std::endl; }
};
int main()
{
Test t;
Callback c;
c.set(t, &Test::foo);
c();
c.set(t, &Test::bar);
c();
}
I recently implemented this:
#define UNKOWN_ITEM 0xFFFFFFFF
template <typename TArg>
class DelegateI
{
public:
virtual void operator()(TArg& a)=0;
virtual bool equals(DelegateI<TArg>* d)=0;
};
template <class TArg>
class Event
{
public:
Event()
{
}
~Event()
{
for (size_t x=0; x<m_vDelegates.size(); x++)
delete m_vDelegates[x];
}
void operator()(TArg& a)
{
for (size_t x=0; x<m_vDelegates.size(); x++)
{
m_vDelegates[x]->operator()(a);
}
}
void operator+=(DelegateI<TArg>* d)
{
if (findInfo(d) != UNKOWN_ITEM)
{
delete d;
return;
}
m_vDelegates.push_back(d);
}
void operator-=(DelegateI<TArg>* d)
{
uint32 index = findInfo(d);
delete d;
if (index == UNKOWN_ITEM)
return;
m_vDelegates.erase(m_vDelegates.begin()+index);
}
protected:
int findInfo(DelegateI<TArg>* d)
{
for (size_t x=0; x<m_vDelegates.size(); x++)
{
if (m_vDelegates[x]->equals(d))
return (int)x;
}
return UNKOWN_ITEM;
}
private:
std::vector<DelegateI<TArg>*> m_vDelegates;
};
template <class TObj, typename TArg>
class ObjDelegate : public DelegateI<TArg>
{
public:
typedef void (TObj::*TFunct)(TArg&);
ObjDelegate(TObj* t, TFunct f)
{
m_pObj = t;
m_pFunct = f;
}
virtual bool equals(DelegateI<TArg>* di)
{
ObjDelegate<TObj,TArg> *d = dynamic_cast<ObjDelegate<TObj,TArg>*>(di);
if (!d)
return false;
return ((m_pObj == d->m_pObj) && (m_pFunct == d->m_pFunct));
}
virtual void operator()(TArg& a)
{
if (m_pObj && m_pFunct)
{
(*m_pObj.*m_pFunct)(a);
}
}
TFunct m_pFunct; // pointer to member function
TObj* m_pObj; // pointer to object
};
template <typename TArg>
class FunctDelegate : public DelegateI<TArg>
{
public:
typedef void (*TFunct)(TArg&);
FunctDelegate(TFunct f)
{
m_pFunct = f;
}
virtual bool equals(DelegateI<TArg>* di)
{
FunctDelegate<TArg> *d = dynamic_cast<FunctDelegate<TArg>*>(di);
if (!d)
return false;
return (m_pFunct == d->m_pFunct);
}
virtual void operator()(TArg& a)
{
if (m_pFunct)
{
(*m_pFunct)(a);
}
}
TFunct m_pFunct; // pointer to member function
};
template <typename TArg>
class ProxieDelegate : public DelegateI<TArg>
{
public:
ProxieDelegate(Event<TArg>* e)
{
m_pEvent = e;
}
virtual bool equals(DelegateI<TArg>* di)
{
ProxieDelegate<TArg> *d = dynamic_cast<ProxieDelegate<TArg>*>(di);
if (!d)
return false;
return (m_pEvent == d->m_pEvent);
}
virtual void operator()(TArg& a)
{
if (m_pEvent)
{
(*m_pEvent)(a);
}
}
Event<TArg>* m_pEvent; // pointer to member function
};
template <class TObj, class TArg>
DelegateI<TArg>* delegate(TObj* pObj, void (TObj::*NotifyMethod)(TArg&))
{
return new ObjDelegate<TObj, TArg>(pObj, NotifyMethod);
}
template <class TArg>
DelegateI<TArg>* delegate(void (*NotifyMethod)(TArg&))
{
return new FunctDelegate<TArg>(NotifyMethod);
}
template <class TArg>
DelegateI<TArg>* delegate(Event<TArg>* e)
{
return new ProxieDelegate<TArg>(e);
}
use it like so:
define:
Event<SomeClass> someEvent;
enlist callbacks:
someEvent += delegate(&someFunction);
someEvent += delegate(classPtr, &class::classFunction);
someEvent += delegate(&someOtherEvent);
trigger:
someEvent(someClassObj);
You can also make your own delegates and overide what they do. I made a couple of others with one being able to make sure the event triggers the function in the gui thread instead of the thread it was called.
You need to use polymorphism. Use an abstract base class with a virtual invocation method (operator() if you please), with a templated descendant that implements the virtual method using the correct type signature.
The way you have it now, the data holding the type is templated, but the code meant to invoke the method and pass the object isn't. That won't work; the template type parameters need to flow through both construction and invocation.
#Barry Kelly
#include <iostream>
class callback {
public:
virtual void operator()() {};
};
template<class C>
class callback_specialization : public callback {
public:
callback_specialization(C& object, void (C::*method)())
: o(object), m(method) {}
void operator()() {
(&o ->* m) ();
}
private:
C& o;
void (C::*m)();
};
class X {
public:
void y() { std::cout << "ok\n"; }
};
int main() {
X x;
callback c(callback_specialization<X>(x, &X::y));
c();
return 0;
}
I tried this, but it does not work (print "ok")... why?
Edit:
As Neil Butterworth mentioned, polymorphism works through pointers and references,
X x;
callback& c = callback_specialization<X>(x, &X::y);
c();
Edit:
With this code, I get an error:
invalid initialization of non-const reference of type ‘callback&’
from a temporary of type ‘callback_specialization<X>’
Now, I don't understand that error, but if I replace callback& c with const callback& c and virtual void operator()() with virtual void operator()() const, it works.
You didn't say what errors you found, but I found that this worked:
template<typename C>
class callback {
public:
// constructs a callback to a method in the context of a given object
callback(C& object, void (C::*method)())
: ptr(object,method) {}
// calls the method
void operator()() {
(&ptr.o ->* ptr.m) ();
}
private:
// container for the pointer to method
// template<class C>
struct Ptr{
Ptr(C& object, void (C::*method)()): o(object), m(method) {}
C& o;
void (C::*m)();
} ptr;
};
Note that Ptr needs a constructor as it has a reference member.
You could do without struct Ptr and have the raw members.
Tested with VS2008 express.
Improving the OP's answer:
int main() {
X x;
callback_specialization<X> c(x, &X::y);
callback& ref(c);
c();
return 0;
}
This prints "ok".
Tested on VS2008 express.
Please see this
Callback in C++, template member? (2)