Reputation: 12581
What is a good way to call a member function of template type? Will the below foo()
code only compile for types that have the bla()
function defined?
class A { void bla(); };
template<typename T>
void foo() {
T t;
t.bla();
}
int main() {
foo<A>();
return 0;
}
Can I use boost::enable_if
to only define this function for types that have a bla()
method? If yes, is that even a good idea? I imagine the idea of "concepts" (which I know nothing about) is possibly what needs to be used here.
Upvotes: 0
Views: 175
Reputation: 7663
For every type you try to invoke the foo function with, the compiler will generate a new foo function with the given it and compile, if you can compile the foo function with a given type, it will works.
So in your case, the foo function will work with every type that have a bla function and that have a default constructor.
Upvotes: 2
Reputation: 146968
It will also only compile for types which are default-constructible. The compiler will throw an error for any type which is not default constructible and does not have a bla()
function that can accept no arguments.
Upvotes: 1
Reputation: 231283
Your code sample looks correct; it will error if instantiated on a type which does not have a bla()
member, of course.
Upvotes: 1