I have a class like this:
template <unsigned int A, unsigned int B>
class Foo { ... };
Foo需要一个名为bar()的方法,但我需要特别处理它。例如,当A == B时,我希望它做一件事情,否则做其他事情。我能否在不将if语句写入函数的情况下实现这一点?像这样:
Foo<A, A>::bar() { ... } and Foo<A, B>::bar() { ... }
I have a class like this:
template <unsigned int A, unsigned int B>
class Foo { ... };
Foo需要一个名为bar()的方法,但我需要特别处理它。例如,当A == B时,我希望它做一件事情,否则做其他事情。我能否在不将if语句写入函数的情况下实现这一点?像这样:
Foo<A, A>::bar() { ... } and Foo<A, B>::bar() { ... }
#include<cassert>
template<typename A, typename B>
struct S {
void f(int i) { assert(i == 42); }
};
template<typename A>
struct S<A, A> {
void f(int i) { assert(i == 0); }
};
int main() {
S<int, double> s1;
S<int, int> s2;
s1.f(42);
s2.f(0);
}
std::is_same<TA,TB>
。#include <iostream>
#include <string>
template <unsigned int A, unsigned int B>
class Foo {
public:
template<unsigned int TA=A, unsigned int TB=B>
typename std::enable_if< TA == TB >::type
bar() {
std::cout << "equal version = " << A << " " << B << "\n";
}
template<unsigned int TA=A, unsigned int TB=B>
typename std::enable_if< TA != TB >::type
bar() {
std::cout << "NON equal version = " << A << " " << B << "\n";
}
};
int main()
{
Foo<1, 1> f1;
f1.bar();
Foo<1, 2> f2;
f2.bar();
return 0;
}
输出:
equal version = 1 1
NON equal version = 1 2
类型化的模板参数示例如下:
http://coliru.stacked-crooked.com/a/05d6a93480e870aa
#include <iostream>
#include <string>
template <typename A, typename B>
class Foo {
public:
template<typename TA=A, typename TB=B>
typename std::enable_if<std::is_same<TA, TB>::value>::type
bar() {
std::cout << "equal version" << "\n";
}
template<typename TA=A, typename TB=B>
typename std::enable_if<!std::is_same<TA, TB>::value>::type
bar() {
// This will cause compilation error if this bar() overload is to be instantiated
// but since it is not there is no compilation error
typename TA::non_exists ii = 0;
std::cout << "NON equal version" << "\n";
}
};
int main()
{
Foo<int, int> f1;
f1.bar();
//Foo<int, float> f2;
//f2.bar();
return 0;
}