【发布时间】:2017-10-24 09:52:40
【问题描述】:
我有一个template <bool P> class Foo,里面有很多代码。我希望能够将Foo<true>'s 转换成Foo<false>'s,即有一个operator Foo<false>() 方法。但是编译器不喜欢 Foo 存在的这种方法,它只喜欢Foo<true>,并警告“不会为隐式或显式转换调用运算符”(GCC 5.4.x)
我似乎不能为此使用 SFINAE:std::enable_if 适用于类型;并且我尝试过的值变体(真正的案例有 value 而不是 type 成员)也没有帮助。
我怎样才能让这个运算符只为Foo<false> 编译(除了专门针对Foo<false> 不同并复制我的所有代码)?
到目前为止,我最好的尝试是:
template <bool P> class Foo {
// etc. etc.
template <bool OtherValue>
operator Foo<OtherValue>()
{
static_assert(OtherValue, "You should not be using this conversion!");
// conversion code here
return Foo<false>(args,go,here);
}
}
【问题讨论】:
-
为什么是转换运算符而不是构造函数?
-
@André - 这并不能解决问题,真的。它仅确保在复制
foo<false>时编译器会抱怨重复定义(假设还存在复制 c'tor)。 -
@André:我不认为我可以让 ctor 只存在于
Foo<false>。但是 - 这是一个想法,我想。
标签: c++ class templates typecast-operator