我正在使用Visual Studio 2008.我有这个类:
template <bool T1>
class Foo {
public:
void doSomething() {}
Foo<T1>& operator=(int a) {
doSomething();
return *this;
}
};
但是如果模板参数operator=
为false,我希望隐藏方法return *this
(只需执行:T1
)。
对于Foo的实例,我需要这些:行:
Foo<false> foo;
foo = 20; //this should give a compilation error
所以我尝试了专门化的类定义:
template<>
class Foo<false> {
private:
Foo<false>& operator=(int a) {
return *this;
}
};
但是,通过这样做,我在doSomething()
的实例上丢失了方法Foo<false>
,这不是我需要的。
我尝试使用boost :: enable_if删除operator=
,如下所示:
typename boost::enable_if<
boost::mpl::bool_<T1>
, Foo<T1>
>::type&
operator=(int a) {
callProxy();
return *this;
}
但这使我无法拥有如下的课程:
class Bar {
public:
Foo<true> assignable;
Foo<false> unassignable;
};
我也尝试将这两种方法放在Foo中并使用boost::enable_if
和boost::disable_if
删除它们,如下所示:
template <bool T1>
class Foo {
public:
void doSomething() {}
typename boost::enable_if<
boost::mpl::bool_<T1>
, Foo<T1>
>::type&
operator=(int a) {
doSomething();
return *this;
}
private:
typename boost::disable_if<
boost::mpl::bool_<T1>
, Foo<T1>
>::type&
operator=(int a) {
return *this;
}
};
哪个也行不通(我希望如此,但值得尝试)。
那么,是否有可能获得我需要的行为,如果是,我该怎么办呢?
答案 0 :(得分:4)
为什么不使用常规的if()?
if(T1) doSomething();
答案 1 :(得分:1)
false
案例不是特殊情况,而是true
案例的特殊情况,在这种情况下只包括operator=
。
答案 2 :(得分:1)
您可以静态断言条件:
Foo<T1>& operator=(int a) {
BOOST_STATIC_ASSERT(T1);
doSomething();
return *this;
}