With dynamic polymorphism I can create interface, that cannot be instantiated, because some methods are pure virtual.
What is the equivalent with static polymorphism?
Consider this example:
template<typename T> string f() { return ""; }
template<> string f<int>() { return "int"; }
template<> string f<float>() { return "float"; }
I want to "disable" the first one, similarly as when I declare a method of a class to be pure virtual.
Question:
What is the equivalent with static polymorphism?
Declare a function template without an implementation. Create implementations only for the types that you want to support.
// Only the declaration.
template<typename T> string f();
// Implement for float.
template<> string f<float>() { return "float"; }
f<int>(); // Error.
f<float>(); // OK
Update
Use of static_assert
:
#include <string>
using std::string;
template<typename T> string f() { static_assert((sizeof(T) == 0), "Not implemented"); return "";}
// Implement for float.
template<> string f<float>() { return "float"; }
int main()
{
f<int>(); // Error.
f<float>(); // OK
return 0;
}
Compiler report:
g++ -std=c++11 -Wall socc.cc -o socc
socc.cc: In function ‘std::string f()’:
socc.cc:6:35: error: static assertion failed: Not implemented
<builtin>: recipe for target `socc' failed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With