将函数模板限制为仅接受模板参数的几个允许值是否被认为是错误的样式?
示例:
template<typename T>
class Foo {
typename std::enable_if<std::is_same<Bar, T>::value, void>::type
callFuncInBar() {
BarGetValue();
}
typename std::enable_if<std::is_same<FooBar, T>::value, void>::type
callFuncInFooBar() {
FooBarGetValue();
}
};
编辑: 我的情况是这样的: 我有两个简单的结构A和B几乎相似:
struct A: public ICompress {
void compress() override {
next->compress();
}
ICompress *next;
};
struct B: public IDecompress {
void decompress() override {
next->decompress()
}
IDecompress *next;
};
我的目的是创建一个应该作为Compressor或Decompressor实例化的模板:
template<typename T>
struct codecomp: public T {
typename std::enable_if<std::is_base_of<ICompress, T>::value, void>::type
compress() {
next->compress();
}
typename std::enable_if<std::is_base_of<IDecompress , T>::value, void>::type
decompress() {
next->decompress();
}
T *next;
};
答案 0 :(得分:2)
如上所述,如果Foo
被实例化,您的代码将无法编译。对于与T
不同的任何类型Bar
,Foo<T>
的实例化将导致Foo<T>::callFuncInBar
的返回类型的实例化,这将失败。同样,如果T
与FooBar
不同,则返回类型callFuncInFooBar
的实例化将失败。
我认为这不是你想要的。
我认为Foo<T>::callFuncInBar
只有T
为Bar
才能调用您真正想要的内容。这通常由模板专业化处理:为Foo<T>
= T
和Bar
= T
专门化类模板FooBar
,并在主模板中不要完全声明callFuncInBar
和callFuncInFooBar
成员函数,因此它们将不可用。这完全避免了你的风格问题; Foo
可以使用任何模板参数进行实例化,但具有取决于特定参数的功能集。 ( 被认为是完美的风格;即使是标准库也可以。)