在C ++中限制允许的模板参数被认为是不好的风格吗?

时间:2017-04-22 08:39:30

标签: c++ templates sfinae

将函数模板限制为仅接受模板参数的几个允许值是否被认为是错误的样式?

示例:

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;
};

1 个答案:

答案 0 :(得分:2)

如上所述,如果Foo被实例化,您的代码将无法编译。对于与T不同的任何类型BarFoo<T>的实例化将导致Foo<T>::callFuncInBar的返回类型的实例化,这将失败。同样,如果TFooBar不同,则返回类型callFuncInFooBar的实例化将失败。

我认为这不是你想要的。

我认为Foo<T>::callFuncInBar只有TBar才能调用您真正想要的内容。这通常由模板专业化处理:为Foo<T> = TBar = T专门化类模板FooBar,并在主模板中不要完全声明callFuncInBarcallFuncInFooBar成员函数,因此它们将不可用。这完全避免了你的风格问题; Foo可以使用任何模板参数进行实例化,但具有取决于特定参数的功能集。 ( 被认为是完美的风格;即使是标准库也可以。)