假设我有一个模板函数,它接受一个整数和一个const引用到类型为T的实例.现在,根据整数,只有一些T是可加入的,否则在运行时抛出异常.
如果此函数的所有使用都使用常量整数,则可以使int成为模板参数并使用静态断言来检查它是否可接受.因此,func(1,c)不会使用func<1>(c)并将获得编译时类型检查.有没有办法编写func(1,c)并仍然保持编译时检查,同时还能够编写func(i,c)和使用动态断言?目标是使其对开发人员透明.添加这种安全性而不打扰开发人员关于编译时常量之类的东西会很棒.他们可能只记得func(1,c)总是有效并且使用它,避免检查.
如何尽可能使用静态断言定义函数,否则动态断言?
以下代码显示了Ivan Shcherbakov的 GCC解决方案:
#include <iostream>
#include <cassert>
template<typename T>
void __attribute__((always_inline)) func(const int& i, const T& t);
void compile_time_error_() __attribute__((__error__ ("assertion failed")));
template<>
void __attribute__((always_inline))
func(const int& i, const float& t)
{
do {
if (i != 0) {
if (__builtin_constant_p(i)) compile_time_error_();
std::cerr << "assertion xzy failed" << std::endl;
exit(1);
}
} while (0);
func_impl<float>(i,t);
}
Run Code Online (Sandbox Code Playgroud)
这只允许i = 0和T = float的组合.对于其他组合,一个好方法是创建一个宏,生成代码为template<> func(const int& i, const …
如果我有两个抽象类定义一个具有相同名称但不同的非协变返回类型的纯虚函数,我如何从这些函数派生并为它们的函数定义一个实现?
#include <iostream>
class ITestA {
public:
virtual ~ITestA() {};
virtual float test() =0;
};
class ITestB {
public:
virtual ~ITestB() {};
virtual bool test() =0;
};
class C : public ITestA, public ITestB {
public:
/* Somehow implement ITestA::test and ITestB::test */
};
int main() {
ITestA *a = new C();
std::cout << a->test() << std::endl; // should print a float, like "3.14"
ITestB *b = dynamic_cast<ITestB *>(a);
if (b) {
std::cout << b->test() << std::endl; // should print …Run Code Online (Sandbox Code Playgroud) c++ overriding virtual-functions multiple-inheritance abstract-base-class