c++ - 为 4 种类型选择 2 个模板函数之一

标签 c++ templates c++11

是否有一种更简洁(“less c++11”)的方法来根据多种类型选择要在此示例中使用的模板函数。我只想拥有 2 个函数,我可以使用额外的 2 或 4 个函数重载或调用实现。

struct A{}; struct B{}; struct C{}; struct D{};

template <typename T>
typename std::enable_if<std::is_same<T, A>::value or std::is_same<T, B>::value, void>::type
foo(T& t)
{ 
    printf("first\n"); 
}

template <typename T>
typename std::enable_if<std::is_same<T, C>::value or std::is_same<T, D>::value, void>::type
foo(T& t)
{ 
    printf("second\n"); 
}

int main()
{
  A a; B b; C c; D d;
  foo(a); foo(b); foo(c); foo(d);
}

最佳答案

less c++11

下面的代码根据修订版 C++98 工作。
它模拟更多的 C++11-ish std::enable_if,仅此而已。

#include<cstdio>

struct A{}; struct B{}; struct C{}; struct D{};

template<typename> struct R1;
template<> struct R1<A> { typedef void type; };
template<> struct R1<B> { typedef void type; };

template<typename> struct R2;
template<> struct R2<C> { typedef void type; };
template<> struct R2<D> { typedef void type; };

template <typename T>
typename R1<T>::type foo(T& t)
{ 
    printf("first\n"); 
}

template <typename T>
typename R2<T>::type foo(T& t)
{ 
    printf("second\n"); 
}

int main()
{
    A a; B b; C c; D d;
    foo(a); foo(b); foo(c); foo(d);
}

cleaner

老实说,我发现 C++11 更简洁,它的 using 声明和 std::enable_if

关于c++ - 为 4 种类型选择 2 个模板函数之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203325/

相关文章:

c++ - SFINAE 是否适用于功能体?

c++ - 将命令模式、工厂模式和模板混合在一起......

c++ - 在模板类中使用 r 和 l 值构造函数时出错

c++ - 组合多个类模板特化

c++ - 插入流的右值引用是否合理有效?

c++ - Catch Lib 问题 - 匿名 namespace 重新定义。怎么解决

c++ - CUDA无法将类拆分为 header 和实现

c++ - move 语义和 std::future

c++ - 分配给派生类的基组件

c++ - 将函数传递给可变函数模板