c++11元编程:检查方法是否存在
c++11 metaprogramming: check for method existence
1)我有两个类class A
和class B
,它们都有一个称为foo
的方法,但具有不同的参数列表。
class A {
public:
void foo(int a);
};
class B {
public:
void foo(int a, int b);
};
2)此外,我有一个class C
模板参数T
,也有一个foo
方法如下
template <typename T>
class C {
public:
void foo();
private:
T t_;
int a_;
int b_;
};
3)我想使用class A
和class B
作为class C
的模板参数。说,我想有一个方法C::foo
实现如下:
template <typename T>
void C<T>::foo()
{
if (compile time check: T has foo(int a, int b))
t_.foo(a_, b_);
else
t_.foo(a_);
}
如何在C++11
中表达上面的if
语句
使用SFINAE(函数模板重载)
template <typename T>
class C {
private:
T t_;
int a_;
int b_;
public:
template <typename X = T>
auto foo() -> decltype (std::declval<X>().foo(a_)) {
t_.foo(a_);
}
template <typename X = T>
auto foo() -> decltype (std::declval<X>().foo(a_, b_)) {
t_.foo(a_, b_);
}
};
生活如果你知道哪种类型包含void foo(int a, int b);
在这种情况下,你可以使用模板特化,比如
template <typename T>
class C
{
private:
T t_;
int a_;
int b_;
public:
// called for general use
void foo()
{
t_.foo(a_);
}
};
// specialized version for T = B
template<>
void C<B>::foo()
{
t_.foo(a_, b_);
}
相关文章:
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 使用类在C++中存储和列出变量/方法是否是一种好的做法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 矢量擦除方法是否需要类才能具有 = 运算符?
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- std::is_invocable 用于测试任意方法是否存在的语法(不仅是运算符())
- 这种获取模板参数包中最后一个元素的方法是否有隐藏的开销?
- 使用范围解析运算符时,在构造函数中调用虚拟方法是否安全?
- c++ 中的抽象方法是否曾经调用过?
- 抽象类/接口中的空方法是否被认为是一种好的做法?
- 当元组给出参数时,如何检查方法是否存在?
- 如何测试基类中的方法是否已使用谷歌模拟调用和执行?
- 在方法中调用方法是否会导致开销
- 在移出向量上调用 size() 方法是否安全?
- 此工厂方法是否会导致争用条件?
- 这种方法是否对分支的预测产生了影响
- 检查启发式方法是否兼容
- 此方法是否不适合在 std::unordered_map 中使用 2D 坐标作为键
- const 类方法是否阻止在类外部分配变量?