I have codes like this:
class Bar {
public:
void print() {
std::cout << "bar\n";
}
};
template<typename T>
class Foo {
public:
template <typename std::enable_if<std::is_base_of<T,Bar>::value,T>::type>
void print() {
t.print();
}
template <typename>
void print() {
std::cout << t << std::endl;
}
private:
T t;
};
int main() {
// Foo<int> foo1;
Foo<Bar> foo2;
foo2.print();
}
The purpose of this code is that: If the T t
is a Bar
or a subclass of Bar
, then foo.print()
is deduced to void print() {t.print();}
, otherwise deduced to void print() {std::cout << t << std::endl;}
, but things didn't work as I expect. The compiler errors:
"a non-type template parameter cannot have type 'typename std::enable_if::value, Bar>::type' (aka 'Bar')",
What's wrong with this code?
template <typename
, an identifier is expected. As intemplate <typename T>
.Your definition ofprint
is not valid C++. – Protist...::type>
to...::type* = nullprt>
and it works, but I don't know why write like this. – Kevinkevina