Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the equivalent of pure abstract function in static polymorphism?

Tags:

c++

templates

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.

like image 566
Ruggero Turra Avatar asked Jan 08 '23 18:01

Ruggero Turra


1 Answers

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
like image 62
R Sahu Avatar answered Feb 01 '23 00:02

R Sahu