静态嵌套bool会帮助我禁用对某些类型的调用吗?或者有更干净的方法吗
Would a static nested bool help me disable a call for certain types or is there a cleaner way?
我有一个模板类,比如:
template<class T>
class someClient
{
void someCallbackA() {foo_->onA();}
void someCallbackB() {foo_->onB();}
private:
T* foo_;
};
我可以用支持CCD_ 1和CCD_。我碰巧遇到这样一种情况,我使用的几种不同类型的T
中有两种需要由someClient
控制的特定行为,所以我需要在这两种类型中添加一些函数doBar()
(称它们为Edge1
和Edge2
)。然后,我希望someClient
代码的一部分调用foo_->doBar()
,但当onA
0的类型没有它时,不要中断。有没有一种方法可以使用boost::enable_if
来拥有一个someClient::doBar()
,它只会对这两种类型调用foo_->doBar()
,但不存在,或者如果类型不是Edge1
或Edge2
,则扩展为无?
我当时的想法是:
template <class T, enable_if<mpl_or<is_same<T,Edge1>, is_same<T,Edge2> > >
someClient<T>::doBar() {foo_->doBar();}
如果不调用没有意义的成员函数,就根本不需要使用任何特殊技巧。模板成员函数只有在需要时才专门化(除非添加了明确的专门化)。因此以下代码运行良好:
template <typename T> struct Foo
{
void do_foo() { p->foo(); }
void do_bar() { p->bar(); }
T * p;
};
struct A { void foo() {} };
int main()
{
A a;
Foo<A> x = { &a };
x.do_foo();
}
Foo<A>::do_bar
不会编译这一事实并不是问题,因为成员函数从未被实例化。p->bar
不是编译器错误,因为p
有一个依赖类型,因此该行只在第二个查找阶段解析(这从未发生)。
我认为这符合您的要求。我使用C++11<type_traits>
而不是boost的:
struct Edge {
void doBar() { std::cout << "did Bar."; }
};
template<typename T>
class someClient
{
public:
template<typename U = T>
typename
std::enable_if<std::is_same<U, Edge>::value, void>::type
doBar() { foo_->doBar(); }
template<typename U = T>
void doBar( typename std::enable_if<!std::is_same<U, Edge>::value, void>::type* = 0 )
{ /* do nothing */ }
private:
T* foo_;
};
int main()
{
someClient<int> i;
someClient<Edge> e;
i.doBar();
e.doBar(); // outputs "did Bar."
}
onB
0需要作为模板本身才能工作,这里的解释是:std::enable_if有条件地编译成员函数
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- Android JNI RegisterNatives:对所有内容调用一次,或者每个函数调用一次
- 调用虚函数的逻辑不清楚(或者是方法隐藏?
- 使用递归模板函数是否会引入函数调用开销,或者编译器是否大部分时间都内联它(下面的示例)?
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- 静态嵌套bool会帮助我禁用对某些类型的调用吗?或者有更干净的方法吗
- C++释放传递给函数中参数的内存,或者将其留给调用方
- 我有一个C++2d数组,我必须调用函数.它只对每5个位置进行平均,例如[0][0]+[5][0]这看起来是否正确,或者有
- 我必须创建一个对象来调用类方法吗?或者我可以只键入类名吗
- c++枚举类型可以作为函数调用吗?或者它只是一种不同风格的类型转换
- 返回右值?或者:为什么复制构造函数在"返回"时被调用<expression>?