What is equivalent to a pure abstract function in static polymorphism?

With dynamic polymorphism, I can create an interface that cannot be created, because some methods are pure virtual.

What is equivalent to static polymorphism?

Consider the following 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, just like when I declare a class method as pure virtual.

+4
source share
1 answer

Question:

What is equivalent to static polymorphism?

Declare a function template without implementation. Create implementations only for the types 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

Usage 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
+9
source

All Articles