Tru*_*uLa 2 c++ templates sfinae c++11
1)我有两个类class A,class B它们都有一个被调用foo但有不同参数列表的方法.
class A {
public:
void foo(int a);
};
class B {
public:
void foo(int a, int b);
};
Run Code Online (Sandbox Code Playgroud)
2)此外,我有一个class Cwith template参数T,它也有一个foo方法如下
template <typename T>
class C {
public:
void foo();
private:
T t_;
int a_;
int b_;
};
Run Code Online (Sandbox Code Playgroud)
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_);
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能表达上述if陈述C++11?
使用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_);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
288 次 |
| 最近记录: |