This question already has answers here:
Restrict C++ Template Parameter to Subclass
(8 answers)
Closed 7 years ago.
Is there any way to make a template only work with child classes of a base class? Something like this:
template<BaseClass T>
class FooBar
{
// ...
};
Either use a static assert from your favourite C++ library (such as this boost example), or put a call in the constructor (or other code which will always be generated when the code is used) to a do-nothing function taking a BaseClass type, for example:
template<class T>
class FooBar
{
public:
FooBar () {
Check(static_cast<T*>(0));
}
private:
void Check ( BaseClasse* ) {}
};
(not tested)
Not directly, but you can test it in the constructor using Boost:
#include <boost/type_traits/is_base_of.hpp>
#include <boost/static_assert.hpp>
template<class T>
class FooBar{
FooBar(){
BOOST_STATIC_ASSERT(boost::is_base_of<BaseClass,T>::value);
}
};
Or if you don't want a static assert, something like this is also nice sometimes:
typedef char ERROR_T_must_be_derived_from_BaseClass[boost::is_base_of<BaseClass,T>::value ? 1 : -1];
Since whoever compiles your code will be brought to this line and has a "readable" error message.
There are ways to make it work with a static assert. See Boost.StaticAssert
Related
This question already has answers here:
Is emulating pure virtual function in static polymorphism using CRTP possible?
(3 answers)
Templated check for the existence of a class member function?
(33 answers)
Closed 1 year ago.
I am using CTRP to define an interface in C++ as follows:
template <typename T>
class Interface {
public:
inline void foo() { static_cast<T*>(this)->foo(); }
};
class Implementation : public Interface<Implementation> {
public:
void foo();
};
Thus, if the Interface is used as such:
template <typename T>
void interfaceUser(Interface<T>& i) {
i.foo();
}
This will end up calling the foo() method of the implementation.
However, the flaw in this method (which I would like to keep because the method names of the interface and implementation are the same), is that, if the implementation does not implement the method, the code still compiles but causes an infinite loop.
My question is, is there some way to use static_assert to compare the pointers of Interface::foo and static_cast<T*>(this)->foo to ensure that they are NOT the same and thus, that the function has been implemented?
Also, please let me know if I am going about this in completely the wrong way.
Thanks
This question already has answers here:
Check if class is derived from a specific class (compile, runtime both answers available)
(6 answers)
Closed 3 years ago.
Suppose I'm writing the following templated function:
class A { /* ... */ };
// ... etc...
template<typename C>
void foo() {
bool C_inherits_A = /* magic */;
if (C_inherits_A) { do_something(); }
else { do_something_else(); }
}
We remember dynamic_cast from the olden days, but that isn't relevant here since there's no pointer, and I'm checking "downward", not "upward". Is there something simple with which to replace /* magic */ in the snippet above?
PS - There should definitely already be a dupe of this question, but I just could not find one so I wrote it up.
Beginning in C++11, the standard C++ library caters to this exact need - using the std::is_base_of type trait. To read a bit more about type traits see their SO tag page.
Anyway, you would replace /* magic */ with:
std::is_base_of<A, C>::value
which is a Boolean expression that's true if A is a base class of C, i.e. if C inherits A.
Remember that type traits are evaluated at compile-time, so you can use if (std::is_base_of<A,C>::value) in constexpr functions, or in template parameters and so on.
This question already has answers here:
automatically convert list of pointers to derived class to list of pointers to base class
(4 answers)
Closed 4 years ago.
I would like to know why the compiler doesn't allow the second use of "print_all" function.
I have to give an example of a bad thing that could happen if the compiler would allow it.
#include <iostream>
#include <list>
using std::list;
class foo {
class bar : public foo {
static void print_all(list<foo *> &L) {
list<foo *> LF;
list<bar *> LB;
print_all(LF); // works fine
print_all(LB); // static semantic error
}
};
};
list<foo *> is an unrelated type to list<bar *>. The function is specified to accept one, but not the other.
But class bar inherits from class foo
That is irrelevant, because the argument of your function isn't foo&. What's relevant is whether list<bar *> inherits list<foo *>. It doesn't. std::list does not have a base class.
This question already has answers here:
Using generic std::function objects with member functions in one class
(6 answers)
Closed 7 years ago.
I know, that this question was already asked here, but I believe that my particular example is unique:
#include <functional>
#include <map>
#include <vector>
class Bar{
public:
static unsigned myFunc(const std::vector<std::string> &input){return 1;};
};
class Foo{
friend class Bar;
public:
using CommandFunction = std::function<unsigned(const std::vector<std::string> &)>;
std::map<std::string, CommandFunction> Commands;
};
int main(){
Foo oFoo;
Bar oBar;
oFoo.Commands["myFunc"] = oBar.myFunc;
return 0;
}
I want to make the myFunc function non-static, so it will be able to access private members of the Bar class. But I have no clue how to implement this idea. Simply removing the static keyword obviously will raise an error during compilation (invalid use of non-static function). Is there any 'clean' way of solving this problem? And by 'clean' I mean not using global variables and objects.
Update
I think I need to clarify the purpose of the design I described above.
I'm using a wrapper to the GNU readline library. It is represented by the Foo class. Basically it holds a set of function pointers inside the Commands map and executes them based on the user input.
The Bar class is a set of functions which share common resources (private members of the Bar class).
Lambda could be a solution for you:
class Bar{
public:
std::function<unsigned(const std::vector<std::string>&)> myFunc{ [](const std::vector<std::string>& x){return 1;}};
};
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Template type deduction in C++ for Class vs Function?
When calling a template function, you don't need to specify the template parameters if they are non-ambiguous from your parameters. E.g. for:
template<typename T> T foo(T a) { /*...*/ }
You can just call foo(1) and it will work, it does not need to be foo<int>(1).
This is not true for classes/structs, even if it would be clear from the constructor parameters. For example:
template<typename T> struct Foo { Foo(T a) { /*...*/ } };
Now I cannot do just a do_something_with(Foo(1)), it must be do_something_with(Foo<int>(1)).
Often, to work around this issue, there are just some simple wrapper functions which basically just wrap the constructor. That is even in the STL: std::make_pair is such an example.
Now the question: Why is that? Is there any rational reason behind it?
As far as I know, function templates and class templates are different for the lulz and there's no real reason that they should be different from each other. Of course, class templates have partial specializations (T*) as an advantage.