使用动态多态,我可以创建无法实例化的接口,因为某些方法是纯虚拟的.
静态多态性的等价物是什么?
考虑这个例子:
template<typename T> string f() { return ""; }
template<> string f<int>() { return "int"; }
template<> string f<float>() { return "float"; }
Run Code Online (Sandbox Code Playgroud)
我想"禁用"第一个,类似于我声明一个类的方法是纯虚拟的.
题:
静态多态性的等价物是什么?
声明没有实现的函数模板.仅为要支持的类型创建实现.
// Only the declaration.
template<typename T> string f();
// Implement for float.
template<> string f<float>() { return "float"; }
f<int>(); // Error.
f<float>(); // OK
Run Code Online (Sandbox Code Playgroud)
更新
使用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;
}
Run Code Online (Sandbox Code Playgroud)
编译报告:
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
Run Code Online (Sandbox Code Playgroud)