静态多态性中的纯抽象函数等价物是什么

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

本文关键字:抽象函数 等价物 是什么 多态性 静态      更新时间:2023-10-16

通过动态多态性,我可以创建无法实例化的接口,因为有些方法是纯虚拟的。

静态多态性的等价物是什么?

请考虑以下示例:

template<typename T> string f() { return ""; }
template<> string f<int>() { return "int"; }
template<> string f<float>() { return "float"; }

我想"禁用"第一个,就像我声明一个类的方法为纯虚拟一样。

问题:

静态多态性的等价物是什么?

声明一个没有实现的函数模板。仅为要支持的类型创建实现。

// Only the declaration.
template<typename T> string f();
// Implement for float.    
template<> string f<float>() { return "float"; }
f<int>();   // Error.
f<float>(); // OK

更新

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;
}

编译器报告:

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