c++ - 如何使用类模板特化避免代码重复

标签 c++ templates c++14 variadic-templates

我想避免下面代码中的重复。

#include <iostream>

struct Bar{};

template <class... Args>
struct FooClass;

template <class... Args>
inline void foo(Args&&... args) {
  FooClass<Args...>::impl(std::forward<Args>(args)...);
}

// Duplicate 1.
// Const ref version
template <>
struct FooClass<Bar const&> {
  inline static void impl(const Bar& b) {
    std::cout << "dup1" << std::endl;
  }
};

// Duplicate 2.
// Copy version
template <>
struct FooClass<Bar> {
  inline static void impl(const Bar& b) {
    std::cout << "dup2" << std::endl;
  }
};

// Duplicate 3.
// Non-const ref version
template <>
struct FooClass<Bar&> {
  inline static void impl(const Bar& b) {
    std::cout << "dup3" << std::endl;
  }
};

int main()
{
  const Bar b2;
  foo(b2);  
  foo(Bar{});
  Bar b;
  foo(b);
}

我很确定这可以通过某种方式使用 enable_if 和通用引用来实现,但我无法弄清楚。

顺便说一句,这个程序输出:

dup1
dup2
dup3

如果三个特化中的任何一个被注释掉,它都不会编译。

最佳答案

为什么不从模板参数中去掉 const& 呢?

template<class... Args>
void foo(Args&&... args) {
    FooClass<std::decay_t<Args>...>::impl(std::forward<Args>(args)...);
    //       ^^^^^^^^^^^^
}

template<>
struct FooClass<Bar> {
    static void impl(const Bar&) {
        std::cout << "bar" << std::endl;
    }
};

int main() {
    const Bar b2;
    foo(b2);       // prints "bar"
    foo(Bar{});    // prints "bar"
    Bar b;
    foo(b);        // prints "bar"
}

Demo

关于c++ - 如何使用类模板特化避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65502524/

相关文章:

c++ - 为什么 glColor3f() 和 glTranslated() 不影响对象创建?

c++ - 具有相似属性的不同数据类型的模板

c++14 模板特化 "used but never defined"

c++ - 这是 gcc 优化器中的错误吗?

c++ - GetTempPath() 写入的内存是否比发送的内存多?

c++ - 具有多种返回类型的函数

templates - 使用 Jinja2,是否可以禁用标签和/或过滤器?

c++ - 使用 constexpr 方法在结构内部进行模板参数化

c++ - 2个模板类 undefined reference 错误的非模板友元函数

c++ - 在 MacOS X Mavericks 上链接 Cuda 应用程序时出错