我试图仅在元组模板参数具有某种特定性的情况下在模板化类中选择性地启用方法。我一直在尝试各种组合,但到目前为止,找不到找到以下代码进行编译的方法。
本质上,当我使用仅包含两个元素的元组实例化foo类时,我希望启用第一个“ void print()”方法,而当我使用其中包含三个元素的元组实例化foo时,就像第二个启用“ void print()”方法一样。
注意:这只是从我要解决的更复杂问题中提炼出来的抽象示例。我还可以使用基于两个特定元组的部分模板专业化来工作。但是我真的很想了解“ enable_if”,我希望它将使我的代码“更简单”。
谢谢
// g++ -std=c++14 a.cc
#include <tuple>
#include <type_traits>
#include <iostream>
using namespace std;
template <class Tuple>
class foo {
public:
Tuple t;
foo(Tuple ta) : t(ta) {
cout<<"constructor\n";
}
//How do I enable this print ONLY if arity of input tuple is 2 ???
typename std::enable_if< std::tuple_size<Tuple>::value == 2, void >::type
print(){
cout<<get<0>(t)<<":"<<get<1>(t)<<"\n";
}
// enable ONLY if arity 3 ???
typename std::enable_if< std::tuple_size<Tuple>::value == 3, void >::type
print(){
cout<<get<0>(t)<<":"<<get<1>(t)<<"::"<<get<1>(t)<<"\n";
}
};
int main(int argc, char**argv) {
typedef tuple<int, double> t2_type;
typedef tuple<int, double, float> t3_type;
t2_type t2(1,2.0);
t3_type t3(100,100.0,2.3);
foo<t2_type> f2(t2);
foo<t3_type> f3(t3);
f2.print();
f3.print();
}
对于上面的特定代码,这里是编译器错误:
% g++ -std=c++14 a.cc
a.cc:25:3: error: ‘typename std::enable_if<(std::tuple_size<_Tp>::value == 3), void>::type foo<Tuple>::print()’ cannot be overloaded
print(){
^
a.cc:19:3: error: with ‘typename std::enable_if<(std::tuple_size<_Tp>::value == 2), void>::type foo<Tuple>::print()’
print(){
^
a.cc: In instantiation of ‘class foo<std::tuple<int, double, float> >’:
a.cc:38:21: required from here
a.cc:19:3: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
a.cc: In function ‘int main(int, char**)’:
a.cc:41:6: error: ‘class foo<std::tuple<int, double, float> >’ has no member named ‘print’
f3.print();
^
GCC详细信息,尽管这应独立于编译器;
% g++ -v
gcc version 4.9.4 (GCC)
解决方案1来自以下答案:
#include <tuple>
#include <type_traits>
#include <iostream>
using namespace std;
template <class Tuple>
class foo {
public:
Tuple t;
foo(Tuple ta) : t(ta) {
cout<<"constructor\n";
}
template <typename T = Tuple>
typename std::enable_if< std::tuple_size<T>::value == 2, void >::type
print(){
cout<<get<0>(t)<<":"<<get<1>(t)<<"\n";
}
// enable ONLY if arity 3 ???
template <typename T = Tuple>
typename std::enable_if< std::tuple_size<T>::value == 3, void >::type
print(){
cout<<get<0>(t)<<":"<<get<1>(t)<<"::"<<get<1>(t)<<"\n";
}
};
int main(int argc, char**argv) {
typedef tuple<int, double> t2_type;
typedef tuple<int, double, float> t3_type;
t2_type t2(1,2.0);
t3_type t3(100,100.0,2.3);
foo<t2_type> f2(t2);
foo<t3_type> f3(t3);
f2.print();
f3.print();
}
您需要制作print
一个模板才能使用enable_if
。您可以为此使用class template参数:
template <typename T = Tuple>
typename std::enable_if< std::tuple_size<T>::value == 2, void >::type
print() {
cout<<get<0>(t)<<":"<<get<1>(t)<<"\n";
}
template <typename T = Tuple>
typename std::enable_if< std::tuple_size<T>::value == 3, void >::type
print() {
cout<<get<0>(t)<<":"<<get<1>(t)<<"::"<<get<1>(t)<<"\n";
}
这是一个演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句