简而言之问题:
如何在纯 c++ 中实现 c++11 中提出的 static if
功能?
历史和原始问题:
最近我想出了一个这样的问题。我需要一个类 Sender
,其接口(interface)类似于
class Sender
{
void sendMessage( ... );
void sendRequest( ... );
void sendFile( ... );
// lots of different send methods, not important actually
}
在某些情况下,我需要创建一个DoubleSender,即这个类的一个实例,它会调用它的方法两次,例如,当调用一个sendMessage(.. .)
方法,同一条消息要发送两次。
我的解决方案:
第一种方法:
有一个 isDouble
成员,并在每个方法调用结束时进行检查
sendMessage(...) { ... if( isDouble ) { sendMessage( ... ); }
好吧,我不想要这个,因为实际上我最近需要重复发布,而时间关键部分的这部分代码将 98% 是被动的。
第二种方法:
从Sender
继承一个类DoubleSender
,并实现其方法如下:
void DoubleSender::sendMessage( ... )
{
Sender::sendMessage(...);
Sender::sendMessage(...);
}
嗯,这是可以接受的,但是会占用大量令人不快的代码空间(真的很多,因为有很多不同的 send..
方法。
第三种方法:
想象一下,我正在使用 c++11 :)。然后我可以使用 static if
:
enum SenderType { Single, Double };
template<SenderType T>
class Sender
{
void sendMessage(...)
{
// do stuff
static if ( T == Single )
{
sendMessage(...);
}
}
};
这比以前的解决方案更短、更易于阅读,不会生成额外的代码,而且...它是 c++11,很遗憾我不能在我的工作中使用它。
所以,这就是我提出问题的地方 - 我如何在 c++ 中实现 static if
模拟?
另外,我希望有任何其他关于如何解决我原来的问题的建议.
提前致谢。
最佳答案
引用@JohannesSchaubLitb
with my static_if that works on gcc one can do it :)
in some limited fashion
(另见 here)
这个技巧涉及对 C++11 中 Lambda 规范的特定 GCC 解释。因此,它将(很可能)成为针对标准的缺陷报告。这将导致该技巧在最新版本的 GCC 中不再有效(它在 4.7 中已经无效)。
See the comment thread below for some more details from Johanness
#include <iostream>
namespace detail {
template<bool C>
struct call_if { template<typename F> void operator<<(F) { } };
template<>
struct call_if<true> {
template<typename F>
void operator<<(F f) { f(); }
};
}
#define static_if(cond) detail::call_if<cond>() << [&]
template<bool C, typename T>
void f(T t) {
static_if(C) {
t.foo();
};
}
int main() {
f<false>(42);
}
关于c++ - 如果在纯 c++ 中是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9941034/